Heading vector from angle (generated by trig) does not have expected result

328 Views Asked by At

I am creating a game and when the player taps on the screen, it should generate a ‘pulse’ effect, pushing away the player.

For example, the heading vector should have negative x and y values when to the top right of the player’s position is tapped.

Given a Cartesian coordinate system, can anyone see any errors in my maths that might be the problem?

oppositeLength = (touchPositionY - playerPositionY);
adjacentLength = (touchPositionX - playerPositionX);
theta = tan-1(oppositeLength / adjacentLength);

playerMass = 0.0000013;

heading = {playerMass * cos(angle), playerMass * sin(angle)};

Here is some test output… (Theta is in radians):

O: -119.500000, A: 87.500000, Theta: -0.938773439

...with vector…:

{7.680115295514375e-07, -1.0488843175016773e-06}

…when the touch position is to the top right of the player position.

1

There are 1 best solutions below

0
On

A couple of coding oddities:

(1) "angle" is never defined. Should it be "theta" ?

(2) You probably should have used Atan2, not Atan.

But there's a much easier way to do this. You don't need to calculate the angle. Just use:

dx = playerPositionX - touchPositionX;
dy = playerPositionY - touchPositionY;
d = Sqrt(dx*dx + dy*dy);

heading = {playerMass * (dx/d), playerMass * (dy/d)};

The vector $(dx,dy)$ goes from the touch position to the player position, so this gives you the "push" direction you need. Multiplying by playerMass and dividing by d just modify the length of this vector.