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:

  1. Track position changes by storing the last known position and comparing it with the current position
  2. Measure time between updates using SDL_GetTicks()
  3. Calculate speed using the formula: speed = distance / time

The distance is calculated using the Pythagorean theorem dx2+dy2\sqrt{dx^2 + dy^2} 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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Calculating Mouse Pointer Angle
How can I get the mouse pointer's angle relative to a position on the screen?
Click and Drag Detection
How do I detect if the user is clicking and dragging?
Events vs State for Mouse Input
What's the difference between using events and using state checking for mouse position?
Smooth Mouse Following
How can I make an object follow the mouse cursor smoothly?
Click-and-Drag Selection
How do I implement a click-and-drag selection rectangle?
Cursor Trail Effect
How do I implement a cursor trail effect?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant