-1

I am trying to write a program where an object moves in a direction at a certain speed. Java does not have any built in function to determine direction. How would I write the Scratch Code below in Java? Also is there a way to make an object point at another object?
Screenshot of Scratch code to make object move in a direction or point toward mouse
I want the code to look like this:

public void move(int direction, int distance) {
    // 0 degrees is up, 90 is right, 180 is down, 270 is left.
}

Also if you feel there is a better way to ask this question, please give me tips, this is my first question on this site.

Ben Moon
  • 13
  • 5
  • 2
    One word: trigonometry. Look at `sin` and `cos` for your first question, then `arctan` for your second. – Silvio Mayolo Dec 03 '17 at 21:21
  • I know that it has to do with trigonometry, but my specific case is a little more complex than that. I edited the question to be a bit more specific. – Ben Moon Dec 03 '17 at 21:37

1 Answers1

0

Well, I figured it out with a friend who's very good at geometry. These are the functions we came up with:

// Movement
public void move(int speed) {
    x += speed * Math.cos(direction * Math.PI / 180);
    y += speed * Math.sin(direction * Math.PI / 180);
}
// Pointing toward an object
public void pointToward(SObject target) {
    direction = Math.atan2(target.y - y, target.x - x) * (180 / Math.PI);
}
// Pointing toward the mouse
public void pointTowardMouse() {
    direction = Math.atan2(Main.mouse.getY() - y, Main.mouse.getX() - x) * (180 / Math.PI);
}
// Ensure that the degrees of rotation stay between 0 and 359
public void turn(int degrees) {
    double newDir = direction;
    newDir += degrees;
    if (degrees > 0) {
        if (newDir > 359) {
            newDir -= 360;
        }
    } else if (degrees < 0) {
        if (newDir < 0) {
            newDir += 360;
        }
    }
    direction = newDir;
}

I guess this can help someone else who needs rotational movement in their game.

Ben Moon
  • 13
  • 5