I would like to know how to stop a the player when touching an object. I have movements set up here but I could not find a way to make my player properly stop when touching objects.
My player's movement code in the player Class:
This is the event listener for when the keys are pressed. The Boolean values become true when pressed.
public function onKeyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.D)
{
isRight = true;
}
if (event.keyCode == Keyboard.A)
{
isLeft = true;
}
if (event.keyCode == Keyboard.W)
{
isUp = true;
}
if (event.keyCode == Keyboard.S)
{
isDown = true;
}
}
This is the the event listener for when the key are not pressed. The Boolean values become false when not pressed.
private function onKeyUp(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.D)
{
isRight = false;
}
if (event.keyCode == Keyboard.A)
{
isLeft = false;
}
if (event.keyCode == Keyboard.W)
{
isUp = false;
}
if (event.keyCode == Keyboard.S)
{
isDown = false;;
}
}
This is the enter frame, vx and vy are int variables and are 0 when keys are not pressed, but they change value when keys are pressed. The vx and vy also add to the player's x and y every frame but when they are 0, the player won't move.
private function onEnterFrame(event:Event):void
{
_vx = 0;
_vy = 0;
if (isRight)
{
_vx = 5;
}
if (isLeft)
{
_vx = -5;
}
if (isUp)
{
_vy = -5;
}
if (isDown)
{
_vy = 5;
}
x += _vx;
y += _vy;
}
You don't need to have many conditions, take a look at this example:
When you press or release A, W, D or S keys, the respective _keys
Objectproperties changes fromtruetofalse.Now, the
hitTestpart. Maybe is better thehitTestPointmethod than thehitestObjectmethod because this last one only checks if the bounds of both objects are touching. While thehitTestPointmethod checks if thepointtouches any of the pixels of theObject.As you move the player every five pixels, it is necessary restore the player to correct position in which it no touch the object (I've made a
whilecycle for this purpose). Depends of your game design, you need to change the code, but this guide you in your purpose:Player's getPoint method
HitTest Code (Game Tick)
Download the example