# Character movement relative to cursor position

I want my top-down shooter character to move towards the mouse when pressing the up arrow and strafe relative at right angles to it when pressing the left and right arrow keys.

I can't figure out how to do this.

Here is my code (The character is character_mc):

import flash.events.MouseEvent;
//Event Listners
crosshair_mc.mouseEnabled = false;

function fl_CustomMouseCursor(event:Event)
{
crosshair_mc.x = stage.mouseX;
crosshair_mc.y = stage.mouseY;
}
Mouse.hide();

//Functions
function facecursor(event):void
{
character_mc.rotation = (180 * Math.atan2(mouseY - character_mc.y,mouseX - character_mc.x))/Math.PI + 90;

}

function fl_KeyboardDownHandler(event:KeyboardEvent):void
{
trace("Key Code Pressed: " + event.keyCode);
if (event.keyCode == 38)
{
character_mc.y = character_mc.y - 5;
}
if (event.keyCode == 40)
{
character_mc.y = character_mc.y + 5;
}
if (event.keyCode == 39)
{
character_mc.x = character_mc.x + 5;
}
if (event.keyCode == 37)
{
character_mc.x = character_mc.x - 5;
}

}


I'm new to actionscript, so example code would be helpful.

The direction to the cursor is given by cursor - character position (in screenspace). This is the direction you want to move towads when moving 'forward'.

So, you would add this direction to your characters position to move towards the mouse cursor. You would then move your character like this:

//assuming scaleFactor is a variable with value < 1.0
character_mc.x = character_mc.x + scaleFactor * (crosshair_mc.x - character_mc.x);
character_mc.y = character_mc.y + scaleFactor * (crosshair_mc.y - character_mc.y);


.. if the 'move forward' key is pressed

But, using this vector directly will move/warp your character directly to the mouse cursor, so you might want to scale it down a bit. Ofc, if you where using vectors, this would be easier (e.g. you could multiply the normalized direction by a speed instead of using a scaleFactor).

To move to either the side, you would need to move to a direction -90° or 90° from the forward direction.

Edit: The distance between the character and mouse cursor influences the above formula, thus the character moves faster the further the mouse is away.

This can be changed to be a constant speed by either calculating a constant direction from the characters rotation (using trigonometric functions) or by normalizing the direction vector. In both cases, the result is multiplied by the characters speed and added to her position.