Movement Maths

closed account (2NywAqkS)
How do I accurately move a particle to the centre (0, 0). My current method is

1
2
3
4
5
6
7
void Particle::Move()
{
	double distance = sqrt((x * x) + (y * y));
	double radian = atan2(x, y);
    x += cos(radian) * 100/distance;
    y += sin(radian) * 100/distance;
}


but this moves them strangely into the corners.

Thanks,
Rowan.
I think you are just going in the wrong direction.

say x = 1 and y = 1, then
radian = pi/4
distance = sqrt(2)

If you add r * cos(theta) to x and r*sin(theta) to y, then you will end up with x = 2 and y = 2.

1
2
3
4
5
6
7
void Particle::Move()
{
    double distance = sqrt((x * x) + (y * y));
    double radian = atan2(x, y);
    x -= distance * cos(radian);
    y -= distance * sin(radian);
}
Last edited on
I guess you're using the atan2() function from cmath. Try atan2(y, x) as the C++ reference states:

http://www.cplusplus.com/reference/clibrary/cmath/atan2/

EDIT:
Also, Stewbond is right about the sign.

EDIT:
Finally, you may want to consider to change a bit of your code to get the following:
1
2
3
4
5
6
7
void Particle::Move()
{
    double distance = min(sqrt((x * x) + (y * y)), 100); // This means the particle will move towards the center with steps of 100, unless the center can be reached within this step
    double radian = atan2(y, x);
    x -= distance * cos(radian);
    y -= distance * sin(radian);
}
Last edited on
closed account (2NywAqkS)
thanks Kyon and Stewbond, you were right, I just needed to swap the y and x around and change it to -= :L
Last edited on
Topic archived. No new replies allowed.