Coding a character to go to the opposite side when exceeding the stage width

94 Views Asked by At

Basically, I've made it so that my "player" in my game doesn't exceed the stage width (only moves along the x axis) and so when it gets to the edge it just stops. However, I want to make it so that if the player exceeds the width on the left side it will flow in from the right and vice versa. This is the code I have at the minute which is what stops it from leaving the stage area:

function movePlayer(e:Event):void {
    player.x = stage.mouseX;
    // Doesn't go off the right or left side.
    if (player.x < 0) {
        player.x = 0;
    } else if (player.x > (stage.stageWidth - player.width)) {
        player.x = stage.stageWidth - player.width;
    }
}

Is there a way I could edit this?

1

There are 1 best solutions below

4
On

You can use the % (modulus) operator to calculate a new position value. Something like:

player.x = player.x % this.stage.stageWidth;