vendredi 25 septembre 2015

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

  • Starting position -1 with direction 2: -1 > 1 > 3 > 3 > 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.

Aucun commentaire:

Enregistrer un commentaire