Search code examples
actionscript-3collision-detectionhittest

Making an object in ActionScript that has 2D movement and stops when it hits a wall


I want To make a square that has keyboard movement (up, down, left, right) and will stop when it hits another object such as a wall.

EDIT: I already have a square and a keyboard layout but if that needs to be something specific then please tell me!


Solution

  • jackson, all you need to do is

    1. Listen for keys
    2. update your character
    3. check for colissions

    You are not beeing specific, but I am 100% sure that if you google a bit more into what you need you will find it as there are tons of flash gaming tutorials.

    Here is a minimal setup

    //needed to update the position
    var velocityX:Number = 0;
    var velocityY:Number = 0;
    //draw the ball
    var ball:Sprite = new Sprite();
    ball.graphics.beginFill(0);
    ball.graphics.drawCircle(0,0,20);
    ball.graphics.endFill();
    addChild(ball);
    ball.x = ball.y = 100;
    //setup keys
    stage.addEventListener(KeyboardEvent.KEY_DOWN, updateBall);
    function updateBall(event:KeyboardEvent):void{
        switch(event.keyCode){
            case Keyboard.RIGHT:
            if(velocityX < 6) velocityX += .25;
            break;
            case Keyboard.LEFT:
            if(velocityX > -6) velocityX -= .25;
            break;
            case Keyboard.DOWN:
            if(velocityY < 6) velocityY += .25;
            break;
            case Keyboard.UP:
            if(velocityY > -6) velocityY -= .25;
            break;
        }
        //update ball position
        ball.x += velocityX;
        ball.y += velocityY;
        //check walls , if collision, flip direction
        if(ball.x > stage.stageWidth || ball.x < 0) velocityX *= -1;
        if(ball.y > stage.stageHeight|| ball.y < 0) velocityY *= -1;
    }
    

    Oviously it's not ideal, but it's basic and it illustrates the points states at the top easily. You might want to use some smooth keys and update your game onEnterFrame.

    Goodluck