1
\$\begingroup\$

These are my Vector2's that I am using for this function.

public Vector2 position = new Vector2();
public Vector2 velocity = new Vector2();
public Vector2 movement = new Vector2();
public Vector2 direction = new Vector2();

Here is the function that I use to move the position vector along an angle. setLocation() just sets the new location of the image.

public void move(float delta, float degrees) {
    position.set(image.getX() + image.getWidth() / 2, image.getY() + image.getHeight() / 2);
    direction.set((float) Math.cos(degrees), (float) Math.sin(degrees)).nor();
    velocity.set(direction).scl(speed);
    movement.set(velocity).scl(delta);
    position.add(movement);
    setLocation(position.x, position.y); // Sets location of image
}

I get a lot of different angles with this, just not the correct angles. How should I change this function to move a Vector2 along an angle using the Vector2 class from com.badlogic.gdx.math.Vector2 within the LibGDX library?

I found this answer, but not sure how to implement it.


Update: I figured out part of the issue. Should convert degrees to radians. However, the angle of 0 degrees is towards the right. Is there any way to fix this? As I shouldn't have to add 90 to degrees in order to have correct heading. New code is below

public void move(float delta, float degrees) {
    degrees += 90; // Set degrees to correct heading, shouldn't have to do this
    position.set(image.getX() + image.getWidth() / 2, image.getY() + image.getHeight() / 2);
    direction.set(MathUtils.cos(degrees * MathUtils.degreesToRadians), MathUtils.sin(degrees * MathUtils.degreesToRadians)).nor();
    velocity.set(direction).scl(speed);
    movement.set(velocity).scl(delta);
    position.add(movement);
    setLocation(position.x, position.y);
}
\$\endgroup\$
  • \$\begingroup\$ What is correct heading? \$\endgroup\$ – Lennart Rolland Nov 8 '14 at 21:43
  • \$\begingroup\$ By convention, in mathematics an angle of 0 radians (or degrees) means pointing to the right. Angles move counterclockwise from there. \$\endgroup\$ – mklingen Dec 8 '14 at 17:24
2
\$\begingroup\$

I think you could switch your cos with sin and vise versa if you're really against adding 90 in your function, but I think adding 90 is a perfectly viable solution. Once a function works, you shouldn't have to care what's inside of it.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.