Search code examples
javavectorlanguage-agnosticdirectionmit-scratch

Scratch-Based Movement in Java


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.


Solution

  • 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.