4 Replies Latest reply on May 28, 2015 8:42 AM by azkianury

# How to limit movieclip movements on stage?

Hi, I want to move my movieclip to the left and right but it keeps moving out of the stage. I want to limit the X movement to the width of my stage.

This is my code for the movieclip movement:

import flash.events.KeyboardEvent;

function moveavatar (event:KeyboardEvent):void

{

if (event.keyCode == 39)

{

avatarmove.x += 10;

}

else if (event.keyCode == 37)

{

avatarmove.x -= 10;

}

}

How do I limit the X movement to the width of my stage so it won't move out of stage? Thank you.

• ###### 1. Re: How to limit movieclip movements on stage?

You can use Math.max and Math.min to limit the x value to the stage. You can also use the keydown test as a Boolean converted to an integer. Which can reduce everything down to one line:

import flash.events.KeyboardEvent;

function moveavatar(event: KeyboardEvent): void {

avatarmove.x = Math.max(0,Math.min(stage.stageWidth,avatarmove.x - int(event.keyCode==37) * 10 + int(event.keyCode==39) * 10))

}

• ###### 2. Re: How to limit movieclip movements on stage?

Hi Colin, thank you so much for replying

I tried your code and it works like a charm when I press the Left Arrow (code 37) but when I press the Right Arrow (code 39) it moves out of stage again.

Do you have any idea what's going on?

Thank you.

• ###### 3. Re: How to limit movieclip movements on stage?

You have the registration point in the top left corner. In my case I had it centered. If you want to keep it like you have it, change to this:

import flash.events.KeyboardEvent;

function moveavatar(event: KeyboardEvent): void {

avatarmove.x = Math.max(0,Math.min(stage.stageWidth-avatarmove.width,avatarmove.x - int(event.keyCode==37) * 10 + int(event.keyCode==39) * 10))

}

• ###### 4. Re: How to limit movieclip movements on stage?

Thank you so much Colin! It really helps!