- Home /
Rotate character to the moving direction problems?
Hi, I made a simple character controller script here :
var speed : float = 6.0;
var jumpSpeed : float = 8.0; var gravity : float = 20.0; var target : Transform; private var moveDirection : Vector3 = Vector3.right;
function Update() {
var controller : CharacterController = GetComponent(CharacterController);
// I use "target" as a world space reference, will that be a problem?
moveDirection = Vector3.Normalize(new Vector3(Input.GetAxis("Horizontal"), 0f,
Input.GetAxis("Vertical")));
moveDirection *= speed;
// Apply gravity
moveDirection.y -= gravity * Time.deltaTime;
// Move the controller
controller.Move(moveDirection * Time.deltaTime);
transform.LookAt(target.position + moveDirection);
}
It uses the horizontal/Vertical inputs as movement, and rotates to the moving direction. It works well when you use the WASD keys to move around ( the object rotates to the moving direction ), but when you release the directional keys, the object immediately bounces back to (0,0,0) rotation... how do I make the object remain facing that moving direction even when you stopped pressing the buttons? Thanks!
Answer by cj_coimbra · Nov 23, 2011 at 04:36 PM
The problem is that when you release the WASD keys, your "transform.LookAt(target.position + moveDirection);" code line will read the (0,0,0), because Input.GetAxis´s calls either vertical or horizontal will always be 0 when no keys are pressed.
My quick and dirty suggestion is that you have a second variable. Always copy the moveDirection to it right after you calculate the moveDirection. Then, you apply LookAt function with moveDirection only when there are WASD keys pressed. Other than that, you apply lookAt with that secondary variable which will happen to have the last read Input.GetAxis´s values before the keys were released.
Another problem, I tried copying the "moveDirection" variable to another variable like you told me to, but I cant seem to copy it BEFORE the horizontal/vertical inputs are released... how do I do this?
To see if the keys are pressed, put your GetAxis code outside.
x = Input.GetAxis("Horizontal");
z = Input.GetAxis("Vertical");
moveDirection = Vector3.Normalize(new Vector3(x, 0f, z));
if (x == 0 && z == 0)
transform.LookAt(target.position + lastDirection);
else
{
transform.LookAt(target.position + moveDirection);
lastDirection = moveDirection;
}