user2005938
user2005938

Reputation: 179

Move in the same angle from point to point?

I need to be able to move my player x and y pixels in the same direction as a point to a point. It's hard to explain, but this is what I am trying to do:

enter image description here

Angles 1 and 2 have to be the same. Point 1 stays the same at (100, 100), however point 2 constantly changes and so must the angles. I have tried this:

moveRectangle.setX(touchEvent.getX());
moveRectangle.setY(touchEvent.getY());
float theta = (float) Math.toDegrees(Math.atan2(touchEvent.getY() - 100,touchEvent.getY() - 100));
float velX = (float) (getSpeed() * Math.cos(theta));
float velY = (float) (getSpeed() * Math.sin(theta));
player.move(velX, velY);

The above code is constantly run when the user puts his finger on moveRectangle (Point 2) and moves it. But the above code does not work. The player just moves in one of two directions. player.move just adds velX and velY velocity. So how can I get the two angles and move the player in the right direction? Thanks.

Upvotes: 2

Views: 544

Answers (3)

nfirex
nfirex

Reputation: 1523

Do you need just to know velocity on X and Y axis? You can do it without using trigonometry (just use Pythagorean theorem).

final float deltaX = touchEvent.getX() - player.x; // player.x is point1.x
final float deltaY = touchEvent.getY() - player.y; // player.y is point1.y
final float length = Maths.sqrt((deltaX)^2 + (deltaY)^2);
final float itterations = length / getSpeed();
final float velX = deltaX / itterations;
final float velY = deltaY / itterations;
player.move(velX, velY);

Or you need a code of player moving in cycle?

Upvotes: 1

Stefan Haustein
Stefan Haustein

Reputation: 18813

Remove Math.toDegrees().

From the Math.sin() / cos() Javadoc:

Parameters:

  • a - an angle, in radians.

Returns:

  • the sine of the argument.

Upvotes: 0

sigpwned
sigpwned

Reputation: 7453

Would it be easier to approach this problem using a cartesian approach (vectors) versus polar approach (angle and magnitude)? So, if the player is at point p0 and the "finger" is at point p1, then the direction the player should be moving v is given by the vector p1-p0. You can then scale the resulting vector v by the player's speed, and add the player's speed to his position. You can do this easily on a frame-by-frame basis.

Upvotes: 2

Related Questions