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)
The smooth following is achieved through linear interpolation (lerp). Each frame, we:
SDL_GetMouseState()
Speed
)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.
Learn how to monitor mouse position and button states in real-time using SDL's state query functions