ActionScript: Move an object with keyboard with absolute controls

In this tip I will show you how to move an object with keyboard with absolute controls.

See also how to move an object with keyboard relative-camera control.

What is the absolute controls?

The direction of your object will be calculated depending the object orientation. (Biohazard, Micro Machines, Gears of War). This code is very usefull if you design a car game.

How to make an absolute control in Flash?

  • Get the arrow key status (key is up/key is down);
  • Move or rotate the object on enter frame with the new velocity (Left and Right keys: rotate, Up key: forward, Down key: backward);
// Assign 4 booleans for the 4 arrow keys
var keyUp = false;
var keyDown = false;
var keyLeft = false;
var keyRight = false;

// Add the keyboard event (KEY_DOWN) on the stage
stage.addEventListener(KeyboardEvent.KEY_DOWN, pressKey);
function pressKey(pEvent)
{
	// If an arrow key is down, switch the value to true to the assigned variable
	if (pEvent.keyCode == 38)
	{
		keyUp = true;
	}
	else if (pEvent.keyCode == 40)
	{
		keyDown = true;
	}
	else if (pEvent.keyCode == 37)
	{
		keyLeft = true;
	}
	else if (pEvent.keyCode == 39)
	{
		keyRight = true;
	}
}
// Add the keyboard event (KEY_UP) on the stage
stage.addEventListener(KeyboardEvent.KEY_UP, releaseKey);
function releaseKey(pEvent)
{
	// If the arrow key is up, switch the value to false to the assigned variable
	if (pEvent.keyCode == 38)
	{
		keyUp = false;
	}
	else if (pEvent.keyCode == 40)
	{
		keyDown = false;
	}
	else if (pEvent.keyCode == 37)
	{
		keyLeft = false;
	}
	else if (pEvent.keyCode == 39)
	{
		keyRight = false;
	}
}

// Set the velocity of the object
var speed = 6;
// And the rotation speed
var rotationSpeed = 5;

// Add an enter frame event on the moving object
myCircle.addEventListener(Event.ENTER_FRAME, circleEnterFrame);
function circleEnterFrame(pEvent)
{
	// Set the default velocity to 0 if no key is pressed
	var velocity = 0;
	if (keyUp)
	{
		// If the key up is pressed set the new velocity to the speed value
		velocity = speed;
	}
	if (keyDown)
	{
		// If the key down is pressed set the new velocity to the half speed value
		velocity =  -  speed / 2;
	}
	if (keyLeft)
	{
		// rotate the object
		pEvent.currentTarget.rotation -=  rotationSpeed;
	}
	if (keyRight)
	{
		// rotate the object
		pEvent.currentTarget.rotation +=  rotationSpeed;
	}

	// Convert the degreeAngle to the radian angle
	var angleRadian = pEvent.currentTarget.rotation / 180 * Math.PI;

	// Move the object with the radian angle and the object speed
	pEvent.currentTarget.x +=  Math.cos(angleRadian) * velocity;
	pEvent.currentTarget.y +=  Math.sin(angleRadian) * velocity;
}

[swf:/wp-content/uploads/2011/02/www.benoitfreslon.com_Move_an_object_with_keyboard_with_absolute_controls.swf 550 400]

Download source: www.benoitfreslon.com_Move_an_object_with_keyboard_with_absolute_controls