(Libgdx) Move Vector2 along angle?

Posted by gemurdock on Game Development See other posts from Game Development or by gemurdock
Published on 2014-06-05T11:15:26Z Indexed on 2014/06/05 15:40 UTC
Read the original article Hit count: 408

Filed under:
|
|

I have seen several answers on here about moving along angle, but I can't seem to get this to work properly for me and I am new to LibGDX... just trying to learn.

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);
}

© Game Development or respective owner

Related posts about libgdx

Related posts about vector