Search code examples
collision-detectionactionscript-2flash-8

ActionScript 2 Wall Collision


I am making my Flash game but... the collisions are my very big problem. I tried every single website, but nothing works.

The code of the player is this:

    onClipEvent(enterFrame){
        if(Key.isDown(Key.RIGHT)) {
            this._x+=3
        }
            if(Key.isDown(Key.LEFT)) {
            this._x-=3
        }
            if(Key.isDown(Key.UP)) {
            this._y-=3
        }
            if(Key.isDown(Key.DOWN)) {
            this._y+=3
        }

    }

Collision:

    if(cityhallLeftWall.hitTest(Player._x+Player._width/2, Player._y, true)){
    Player._x -=0
    }
    if(cityhallRightWall.hitTest(Player._x-Player._width/2, Player._y, true)){
    Player._x +=0
    }
    if(cityhallTopWall.hitTest(Player._x, Player._y+Player._height/2, true)){
    Player._y +=0
    }
    if(cityhallBottomWall.hitTest(Player._x, Player._y-Player._height/2, true)){
    Player._y -=0
    }

The movieclip of the player is named "Player". The movieclip of the building is named "cityhall". So, I want for example when the movieclip Player touches the movieclip cityhall, the y and x speed to get 0 or something like that. It's just impossible to find solution, so I decided to ask for help here.

Thanks :)


Solution

  • The problem lies in the Player's coordinates. They are not global.

    Try this in your collision function:

    // store player's new local position in an object
    var playerGlobalPosition = {
        x:Player._x,
        y:Player._y
    };
    
    // translate local position to global
    Player.localToGlobal(playerGlobalPosition);
    

    Then test against those global coordinates:

    if(cityhallLeftWall.hitTest(playerGlobalPosition.x + (Player._width/2), playerGlobalPosition.y, true)){
        Player._x -= 3; // as mentioned before, replace those 0 values with 3
    }
    

    Explanation:

    In the hitTest method the x and y coordinates are defined in the global coordinate space. So if our coordinates (Player._x and Player._y) are local, we should translate them to the global space before applying the method. More here and here