ActionScript: Move an object with keyboard with camera relative control

In this tip I will show you how to move an object with keyboard with camera relative control.

What is a camera relative control?

The direction of your object will be calculated depending the camera position. (Mario 64, Uncharted, GTA 3, etc.).
Eg: If press the right button the character will go on the right.

How to make a camera relative control?

  • Get the arrow key status (key is up/key is down)
  • Set the direction vector
  • Move the object on enter frame with the direction vector
// 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;

// Add an enter frame event on the moving object
myCircle.addEventListener(Event.ENTER_FRAME, circleEnterFrame);
function circleEnterFrame(pEvent) {
	// Create a 2D vector in order to get the object direction according the arrow keys
	var vector = new Point(0,0);
	if (keyUp) {
		// If keyUp is true add the -1 value on the y axis
		vector.y +=  -1;
	}
	if (keyDown) {
		// If keyDown is true add the 1 value on the y axis
		vector.y +=  1;
	}
	if (keyLeft) {
		// If keyLeft is true add the -1 value on the x axis
		vector.x +=  -1;
	}
	if (keyRight) {
		// If keyRight is true add the 1 value on the x axis
		vector.x +=  1;
	}

	// Get the radian angle of the direction
	var angle = Math.atan2(vector.y,vector.x);

	// If vector lenght is not null
	if (vector.length > 0) {
		// Move the object with the angle and the object speed
		pEvent.currentTarget.x +=  Math.cos(angle) * speed;
		pEvent.currentTarget.y +=  Math.sin(angle) * speed;
	}
}

[swf:/wp-content/uploads/2011/01/www.benoitfreslon.com-Move-an-objet-with-keyboard-with-camera-relative-control.swf 550 400]
Donwload source: www.benoitfreslon.com-Move-an-objet-with-keyboard-with-camera-relative-control.zip