Yes! To calculate mouse speed, you'll need to track both the current and previous positions of the mouse, then calculate the distance moved over time. Here's one way to do it:
#include <SDL.h>
#include <cmath>
#include <iostream>
#include "Window.h"
class MouseTracker {
public:
void Tick() {
// Get current mouse position
int CurrentX, CurrentY;
SDL_GetMouseState(&CurrentX, &CurrentY);
// Get current time in milliseconds
Uint32 CurrentTime = SDL_GetTicks();
// Calculate time difference
float DeltaTime = (CurrentTime - LastTime)
/ 1000.0f;
// Calculate distance moved
float DX = CurrentX - LastX;
float DY = CurrentY - LastY;
float Distance = std::sqrt(
DX * DX + DY * DY);
// Calculate speed (pixels per second)
float Speed = Distance / DeltaTime;
if (Distance > 0) {
std::cout << "Mouse speed: "
<< Speed << " pixels/second\n";
}
// Store current values for next frame
LastX = CurrentX;
LastY = CurrentY;
LastTime = CurrentTime;
}
private:
int LastX{0};
int LastY{0};
Uint32 LastTime{SDL_GetTicks()};
};
int main(int argc, char** argv) {
SDL_Init(SDL_INIT_VIDEO);
Window GameWindow;
MouseTracker Tracker;
SDL_Event E;
while (true) {
while (SDL_PollEvent(&E)) {
// Handle other events...
}
Tracker.Tick();
GameWindow.Update();
}
SDL_Quit();
return 0;
}
Mouse speed: 245.8 pixels/second
Mouse speed: 312.3 pixels/second
Mouse speed: 178.9 pixels/second
The speed calculation involves three main steps:
SDL_GetTicks()
The distance is calculated using the Pythagorean theorem to get the actual distance moved, even when moving diagonally.
You might want to smooth out the speed values using a moving average if you need more stable readings, as raw mouse movement can be quite jittery. You could also calculate separate X and Y speeds if you need directional velocity information.
Remember that this gives you speed in pixels per second. If you need the speed in a different unit (like game units), you'll need to convert the pixel distances accordingly.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to monitor mouse position and button states in real-time using SDL's state query functions