PDA

View Full Version : [AS3] Character move past the edge of the screen


rensk
03-30-2010, 01:35 PM
Hello everyone. i am trying to make some things in flash and i already got a character to move but when it comes to the edge of the screen it just moves past it. i want it to stop at the edge. i tried to find what i need on other forums but i couldnt get it to work.

this is my code so far


var rightArrow:Boolean;
var leftArrow:Boolean;
var speed:int = 3.5;

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
stage.addEventListener(Event.ENTER_FRAME, everyFrame);

function keyPressed(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.RIGHT) {
rightArrow = true;
}
if (event.keyCode == Keyboard.LEFT) {
leftArrow = true;
}

}
function keyReleased(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.RIGHT) {
rightArrow = false;
}
if (event.keyCode == Keyboard.LEFT) {
leftArrow = false;
}

}
function everyFrame(event:Event):void {
if (rightArrow) {
ball.x += speed;
}
if (leftArrow) {
ball.x -= speed;
}

}

kdittyr
03-30-2010, 01:46 PM
You are going to want to do some checking for the edge of the flash area:

You will need to grab the size of the flash area:

var stage_width:int = stage.stageWidth;

var stage_height:int = stage.stageHeight;


And then when you are moving the ball, you need to check for the edge:

function everyFrame(event:Event):void {
if (rightArrow && ball.x < (stage_width - ball.width)) {
ball.x += speed;
}
if (leftArrow && ball.x > 0) {
ball.x -= speed;
}
}


You may want to clean it up a little bit and subtract the ball width from the stageWidth when setting the stage_width variable, that way you won't have to do the math every time you run the function everyFrame

var stage_width:int = stage.stageWidth - ball.width;

var stage_height:int = stage.stageHeight - ball.height;
...
function everyFrame(event:Event):void {
if (rightArrow && ball.x < stage_width) {
ball.x += speed;
}
if (leftArrow && ball.x > 0) {
ball.x -= speed;
}
}


You will certainly want to clean up my code, there are probably much better ways to handle this but I wanted to get something to you before my 10 am meeting :)

You would certainly want to check if ball.x += speed is greater than stage_width as well, because that would start pushing off the screen. At least you have something to start with.

rensk
03-30-2010, 01:51 PM
I only need to check left and right because my character cant move up. and when i use this code it still moves through the edge of the screen.

rensk
03-30-2010, 01:56 PM
Oh i got it now i used your code the wrong way :)

Thnx for the help.