Mouse State

Smooth Mouse Following

How can I make an object follow the mouse cursor smoothly?

Abstract art representing computer programming

To create smooth mouse following, we need to implement interpolation between the current object position and the mouse position. Here's how to create a smoothly-following object:

#include <SDL.h>
#include <cmath>
#include <iostream>
#include "Window.h"

class FollowingObject {
public:
  void Tick() {
    // Get current mouse position
    int MouseX, MouseY;
    SDL_GetMouseState(&MouseX, &MouseY);

    // Calculate distance to mouse
    float DX = MouseX - X;
    float DY = MouseY - Y;

    // Move towards mouse with smooth interpolation
    // Adjust for different follow speeds
    float Speed = 0.1f;
    X += DX * Speed; 
    Y += DY * Speed; 

    // Round to nearest pixel for display
    int DisplayX{
      static_cast<int>(std::round(X))};
    int DisplayY{
      static_cast<int>(std::round(Y))};

    std::cout << "Object position: ("
      << DisplayX << ", " << DisplayY
      << ") Mouse: (" << MouseX
      << ", " << MouseY << ")\n";
  }

private:
  // Using floats for smooth movement
  float X{0.0f};
  float Y{0.0f};
};

int main(int argc, char** argv) {
  SDL_Init(SDL_INIT_VIDEO);
  Window GameWindow;
  FollowingObject Follower;
  SDL_Event E;

  while (true) {
    while (SDL_PollEvent(&E)) {
      // Handle other events...
    }

    Follower.Tick();
    GameWindow.Update();
  }

  SDL_Quit();
  return 0;
}
Object position: (50, 60) Mouse: (100, 100)
Object position: (55, 64) Mouse: (100, 100)
Object position: (59, 67) Mouse: (100, 100)
Object position: (63, 70) Mouse: (100, 100)

How It Works

The smooth following is achieved through linear interpolation (lerp). Each frame, we:

  1. Get the current mouse position using SDL_GetMouseState()
  2. Calculate the distance to the mouse
  3. Move a percentage of that distance (controlled by Speed)

Advanced Techniques

For even smoother movement, you can implement:

#include <SDL.h>

class AdvancedFollower {
public:
  void Tick() {
    int MouseX, MouseY;
    SDL_GetMouseState(&MouseX, &MouseY);

    // Get frame time for consistent speed
    float DeltaTime = GetDeltaTime();

    // Calculate spring physics
    float SpringStrength = 8.0f;
    float Damping = 0.8f;

    // Update velocity
    VelocityX += (MouseX - X)
      * SpringStrength * DeltaTime;
    VelocityY += (MouseY - Y)
      * SpringStrength * DeltaTime;

    // Apply damping
    VelocityX *= Damping;
    VelocityY *= Damping;

    // Update position
    X += VelocityX * DeltaTime;
    Y += VelocityY * DeltaTime;
  }

private:
  float X{0.0f}, Y{0.0f};
  float VelocityX{0.0f}, VelocityY{0.0f};

  float GetDeltaTime() {
    static Uint32 LastTime = SDL_GetTicks();
    Uint32 CurrentTime = SDL_GetTicks();
    float DeltaTime = (CurrentTime - LastTime)
      / 1000.0f;
    LastTime = CurrentTime;
    return DeltaTime;
  }
};

This version adds spring physics and velocity for more natural movement. You can adjust SpringStrength and Damping to change the following behavior.

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