What's wrong with my code?

I don't see what I'm doing wrong.

1
2
3
4
5
6
7
8
9
10
sf::Vector2f delta;
		float distance;

		delta.x = targetPos.x - pos.x;
		delta.y = targetPos.y - pos.y;
		distance = sqrt((delta.x * delta.x) + (delta.y * delta.y));
		velocity.x = delta.x / distance;
		velocity.y = delta.y / distance;

		sprite.move(velocity.x, velocity.y);
#define wrong
Sorry.

The sprite is supposed to follow targetPos. It doesn't. The sprite just acts weird when I run it.
By acting weird I mean it just goes in random directions when I move the mouse around.
What happens when distance = 0; ? Maybe do this?

1
2
3
4
if (distance != 0.0f) {
   velocity.x = delta.x / distance;
   velocity.y = delta.y / distance;
}


I'm not sure if you're using the C++ sqrt function on a Windows computer, which has it's own problems, sqrt function of SF, or another OS altogether (I'd assume the first). I swore I remember there being a computational error on Windows machines when calculating square roots, but I can't seem to find any references to it online.

Someone correct me if I'm wrong. -.-
You can't compare floats like that though Volatile. It would be best with ints unless you want to use < and > operators but still not as accurate as ints.
I don't think that's the current problem, Volatile, because it never becomes 0.
I finally read the issue you're having (I had assumed you were having a seg fault error or something). But if you're following the mouse around, why can't you just do sprite.move(mouse.x, mouse.y) if you're trying to have the sprite follow the mouse. Otherwise, plant some numbers in, just say the sprite is at 100,100 and you move the mouse by 10 in either direction. Does the math reflect the desired result?
Topic archived. No new replies allowed.