Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Smoothing mouse movement  (Read 2914 times)

0 Members and 1 Guest are viewing this topic.

mentor

  • Newbie
  • *
  • Posts: 31
    • View Profile
Smoothing mouse movement
« on: October 19, 2014, 06:07:42 pm »
Hi,

I'd like to move a sprite by moving a mouse. First, I decided to use a setPosition() method:

Code: [Select]
double mx, my;
mx = my = 0.f;

...

//in main loop
mx = Mouse::getPosition().x;
my = Mouse::getPosition().y;

mysprite.setPosition(mx, my);

And it actually did the trick, but it's definitely not the perfect solution. Because Mouse::getPosition() returns Vector2i the movement is not smooth and you can clearly see that. So I did this:

Code: [Select]
double mx, my, lastMX, lastMY;
mx = my = lastMX = lastMY = 0.f;

...

//in main loop
mx = Mouse::getPosition().x;
my = Mouse::getPosition().y;

mysprite.move((mx - lastMX), (my - lastMY));

lastMX = Mouse::getPosition().x;
lastMY = Mouse::getPosition().y;

It's not bad, the movement is smoother, but still I think it can be done better. I tried to multiply (mx - lastMX) and (my - lastMY) by deltatime and some constant speed, but that was... Ugh, not good. I'm out of ideas. What can I do to make a mouse movement smooth?
« Last Edit: October 19, 2014, 06:09:32 pm by mentor »

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6286
  • Thor Developer
    • View Profile
    • Bromeon
Re: Smoothing mouse movement
« Reply #1 on: October 19, 2014, 06:47:40 pm »
It's not bad, the movement is smoother
I don't see how it can possibly be smoother. You assign again the mouse position to the coordinates, i.e. despite using double the X and Y values are always integral. The fact that you call move() instead of setPosition() changes nothing, it only accumulates rounding errors.

And use vectors, not components -- that's why they exist. Then you don't have several useless calls to sf::Mouse methods, either. Your first code can be written as:
sf::Vector2i pos = sf::Mouse::getPosition();
sprite.setPosition(static_cast<sf::Vector2f>(pos));
or alternatively:
sf::Vector2f pos(sf::Mouse::getPosition()); // explicit constructor converts int -> double
sprite.setPosition(pos);

Concerning your original question, are you sure that single pixel movement is really an issue? You cannot have higher resolution, the only thing that can be done is to display a pixel as a mix of multiple colors in the texture. That may look smooth in some cases, while in others it looks blurry and distorted.

In general, what do you expect as "smooth"? When you don't trace the cursor anymore, the application may quickly become user-unfriendly. Is your framerate just too low, leading to delayed or stuttering mouse movement?
« Last Edit: October 19, 2014, 06:54:07 pm by Nexus »
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development: