Calculating Mouse Speed
Can I get the mouse speed or how fast it's moving?
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
How It Works
The speed calculation involves three main steps:
- Track position changes by storing the last known position and comparing it with the current position
- Measure time between updates using
SDL_GetTicks()
- Calculate speed using the formula: speed = distance / time
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.
Mouse State
Learn how to monitor mouse position and button states in real-time using SDL's state query functions