- Home /
Have a character face their moving direction?
I am workng with this script
var controller : CharacterController = GetComponent(CharacterController);
var forward = transform.TransformDirection(Vector3.forward);
var curSpeed = speed * Input.GetAxis ("Vertical");
transform.Rotate(0, Input.GetAxis ("Horizontal") * rotateSpeed, 8);
controller.SimpleMove(forward * curSpeed);
It works by rotating the player with the left and right arrows, and actually moving the character forward/backwards with the veritcal keys. How do I manipulate THIS script to make the character walk AND face a direction with the left and right keys just like the forward and backward keys?
I've tried making a 2nd curSpeed var:
var curSpeed2 = speed*(Input.GetAxis("Horizontal");
but I am lost when it comes to plugging that in to the rest of the code...
controller.SimpleMove(forward * curSpeed + curSpeed2);
doesn't work.
Any help is appreciated!
Answer by Peter G · Feb 10, 2011 at 02:29 AM
Here is the easiest way:
if(forward.magnitude > .2) {
//Add a conditional to prevent snapping back
transform.forward = forward;
//Set the transform's forward Vector to your move direction.
}
There are move complicated things you can do with rotation if you want different effects such as smooth rotation, but this will have your character snap to the direction they are moving.
//Off the top of my head //There are some snapping back issues, you would need to rearrange variable's scope and conditionals. //So, sorry, this code is only partially functional. It's more about the concept.
if(forward.magnitude > .2) { //Add a conditional to prevent snapping back var desiredRotation = Quaternion.LookRotation(forward); transform.rotation = Quaternion.Slerp(transform.rotation, desiredRotation, Time.deltaTime); }
I understand the logic here ( move in any direction-forward/back/left/right and face that way), but when I applied it to the script, the player stopped rotating completely. What am I missing here?
Well, when I look at your code, you cannot add a scalar type (a float) and a Vector type as you do in your last snippet so you need some parenthesis for order of operations.
As far as movement goes, you probably want to make a new Vector not based on the character's direction. moveDirection = new Vector3(HorizontalInput moveSpeed, 0, VerticalInput moveSpeed);