Mouse State

Calculating Mouse Speed

Can I get the mouse speed or how fast it's moving?

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 67 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved