Search code examples
javaif-statementpositionboundary

Java: entity going from one side to the other within boundaries


I am trying to write code for an entity which hops from one side of the page to the other until it reaches a boundary, at which point it turns and hops to the opposite direction. 4 and -4 are my boundaries and also maximum position on either side.

Examples on how position is supposed to change:

  • Starting position 0 with direction 2: 0 > 2 > 4 > 2 > 0 > ... But instead I am getting 0 > 2 > 4 > 0 > -2

  • Starting position -1 with direction 2: -1 > 1 > 3 > 3 > 1 > ... But instead I am getting -1 > 1 > 3 > 1 > -1

I'm importing my position and direction from a scanner method. This is the part of my code I am having trouble with:

    public void methodSample() {

    if (position + direction > 4) {
        position = 8 - (position + direction);
        direction = - direction;
    }

    if (position + direction < -4) {
        position = -8 - (position + direction);
        direction = - direction;
    }

    else {
        position = position + direction;
    }}

But I am getting completely irrelevant values when I run the code. It would be great if anyone can spot where I'm going wrong with my code.


Solution

  • What you're trying to do is something like this:

    • If your entity would go off the right edge, then switch direction and go left;
    • If your entity would go off the left edge, then switch direction and go right;
    • If neither is true, go in the same direction.

    However, that's not what's happening. What really happens is this:

    • If your entity would go off the right edge, then switch direction and go left and then take another step left.

    This is because you're missing an "else". If position + direction > 4, then your program executes the code in the first if. But, since there's no else on the second if, the program then continues to the second if. Since position + direction < -4 is now false, the program executes the else part. That means that when you hit the right edge, the program executes both the body of the first if statement and the else part of the second if statement. Changing the second if to else if will fix this.