jeudi 31 décembre 2015

AS3 - How to properly stop player with hitTestObject and restrict player's movement based on colliding area?

I've got a player that has to stop moving on when colliding, but only based on the x/y area of the object. While it touches the left/right sides of the bounding box, it should still be able to move up and down. While it touches the top/bottom sides of the bounding box, it should be able to move side to side.

However I have two issues, the player can glitch through the object when pressing the keys multiple times and both the player's x and y movement would stop once touching any side of the object.

My movement code inside player's class enterframe:

private function onEnterFrame(event: Event): void
{
    _vx = 0;
    _vy = 0;

    if (isRight)
    {
        _vx = 5;
    }
    if (isLeft)
    {
        _vx = -5;
    }
    if (!isJumping && isUp)
    {
        _vy = -5;
    }
    if (!isJumping && isDown)
    {
        _vy = 5;
    }

    x += _vx;
    y += _vy;
}

My hitTestObject code in base class enterframe

private function onEnterFrame(event: Event): void
{
    if (MovieClip(parent).player.collisionArea.hitTestObject(this))
    {
        if (MovieClip(parent).player.isLeft)
        {
            MovieClip(parent).player.x -= MovieClip(parent).player._vx;
        }
        if (MovieClip(parent).player.isRight)
        {
            MovieClip(parent).player.x -= MovieClip(parent).player._vx;
        }
        if (MovieClip(parent).player.isUp)
        {
            MovieClip(parent).player.y -= MovieClip(parent).player._vy;
        }
        if (MovieClip(parent).player.isDown)
        {
            MovieClip(parent).player.y -= MovieClip(parent).player._vy;
        }
    }
}

However, I think my tactic of movement and collision may be incorrect.

FLA file: http://ift.tt/1YR6T7K

The FLA file includes a player and a bed for it to collide with.

Aucun commentaire:

Enregistrer un commentaire