- Home /
Player rotation affecting Top Down 2D Movement
As I'm attempting to control my character, from the perspective of the camera, when S is pressed, the character -always- moves directly south. However, the W,A,D keys move the character in a general north, east or west direction, respectively, As the player rotates via the mouse, the exact direct and speed changes.
Heres'a video of the behavior: http://www.youtube.com/watch?v=RosabgyZ2CE
And here's my code:
#pragma strict
var speed : float = 20.0;
private var moveDirection : Vector3 = Vector3.zero;
function Update () {
var controller : CharacterController = GetComponent(CharacterController);
moveDirection = Vector3(Input.GetAxis("Horizontal"),Input.GetAxis("Vertical"), 0);
moveDirection = Camera.main.transform.TransformDirection(moveDirection);
moveDirection *= speed;
// Move the controller
controller.Move(moveDirection * Time.deltaTime);
var position = Input.mousePosition;
var newPosition = Vector3(position.x, position.y, Camera.main.transform.position.y - transform.position.y);
var lastPosition = Camera.main.ScreenToWorldPoint(newPosition);
transform.LookAt(lastPosition);
}
@script RequireComponent(CharacterController)
Any suggestions or help would be greatly appreciated.
That cube was spinning like a banshee. Try putting in some landmarks and doing thorough testing: turn 60 degrees, wait, move forward, turn 60 more degrees, wait, move forward. Try moving U,L,D...really fast without turning at all. $$anonymous$$eep going until you see exactly what does and doesn't cause the problem movement.
Also, does the camera ever tilt? If it never does, using "camera perspective" is pointless -- just put Horiz and Vert in the proper x,y,z slot.
Answer by Piflik · Apr 27, 2012 at 07:16 AM
Try
moveDirection = (transform.forward * Input.GetAxis("Vertical") + transform.right * Input.GetAxis("Horizontal")) * speed;