Moving a sprite to a position (weird results!)

Apr 15, 2013 at 3:54am
So I'm using SFML 2. I'm making an RTS, and I'm working on the unit moving at the moment. Pretty straight forward: you click a position, the selected unit(s) move there. Simple, right?

So here's my code for the movement. It works for the most part.. But not really.
Basically, when your mouse is in the middle of your Y axis (768 / 2), it works. Perfectly. But when you slowly go up the y axis (- or +), the sprite gets A LOT faster. When you're around 0 / 768, you don't even see the sprite move. Which brings me to my final problem..

When the sprite gets there (normal speed or not), the sprite disappears from the screen! Being the clever guy I am (totally not a lie), I found these were the values of the sprite:
X = -2147483648
Y = -2147483648

Whaaaat! Makes no sense, right? Well, here's the code. You're welcome make fun of it all, just tell me another and better way.

Thank you a lot if you got through all of this text. You're a life saver!

Unit.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
void Unit::Move(sf::RenderWindow& Window)
{
	static int targetX;
	static int targetY;
	static float angleX;
	static float angleY;
	static float distance;
	static float directionX;
	static float directionY;
	static float velocityX;
	static float velocityY;
	
	positionX = sprite.getPosition().x;
	positionY = sprite.getPosition().y;
	

	if(selected == true && sf::Mouse::isButtonPressed(sf::Mouse::Right))
	{
		sprite.move(velocityX, velocityY);
	}

	targetX = sf::Mouse::getPosition(Window).x;
	targetY = sf::Mouse::getPosition(Window).y;
	angleX = sf::Mouse::getPosition(Window).x - sprite.getPosition().x;
	angleY = sf::Mouse::getPosition(Window).y - sprite.getPosition().y;
	distance = sqrt((angleX * angleX) + (angleY + angleY));
	directionX = angleX / distance;
	directionY = angleY / distance;
	velocityX = directionX * speed;
	velocityY = directionY * speed;

}
Apr 15, 2013 at 4:55am
Problem #1:

None of those variables should be static.

The velocity should probably be a member of Unit, whereas all the other ones should be non-static local vars.

This would be a problem if you have multiple Units.

------

Problem #2:

Once the unit reaches its target... distance becomes 0. Dividing by 0 (lines 27, 28) would result in NaN which might explain why your sprite is flying offscreen rapidly.


------

Problem #3:

Line 26: (angleY + angleY) should be (angleY * angleY)
Apr 15, 2013 at 8:39am
Oh my god, thank you so much. I didn't even see that plus sign. That also fixed the disappearing sprite!

Thank you for the static tip too. I guess I'll have to put it in the class.. I don't know why I tried static.

Thank you again. :)
Topic archived. No new replies allowed.