- Home /
How do I move a CharacterController type in the direction it's facing?
I should mention this is an NPC and needs to operate without input from the player. I'd like to drop this NPC somewhere in the game and then use the Editor's rotate tool to point him in the direction I want him to walk forward.
My Code:
function FixedUpdate()
{
moveDirection = Vector3.forward;
moveDirection *= speed;
// Apply gravity
moveDirection.y -= gravity * Time.deltaTime;
// Move the controller
var controller : CharacterController = GetComponent(CharacterController);
var flags = controller.Move(moveDirection * Time.deltaTime);
grounded = (flags & CollisionFlags.CollidedBelow) != 0;
}
When the game runs, my character moves in the Vector3.forward direction, however if I rotate him to point in a different direction (lets say 45 degrees) and start the game, then he's facing 45 degrees but is still moving in Vector.forward. I'm guessing the rotation isn't changing his Z-axis(?)...
The only thing I could think of is to take the rotation angle he's facing and figure out a way to calculate how much Z and how much X to put in his "moveDirection." For example if his rotation is 45 degrees then he's in the middle between the Z and X axis; so that's Vector3(0.5,0,0.5) 50% X-axis and 50% Z-axis. I'm guessing there's an easier way then trying to compute it manually...
I tried another solution on Unity Answers that suggested to use "transform.LookAt" but his solution didn't work for me: http://answers.unity3d.com/questions/5364/how-can-i-get-my-model-to-face-the-direction-it-is-moving
Thank you in advance!
Answer by spinaljack · Jul 24, 2010 at 11:24 AM
Vector3.forward is on the world axis.
You need local rotation or transform direction
e.g.
moveDirection = transform.TransformDirection(Vector3.forward)*moveSpeed;
Thank you spinaljack and $$anonymous$$ike; BOTH of your solutions worked. (I had to remove the "*moveSpeed"). Again thank you both very, very much!!!! @$$anonymous$$ike- I wish your answer was here so I could give you credit as well.
Your answer
Follow this Question
Related Questions
Movement based on camera 1 Answer
How can I get my character to face the direction he is moving? 1 Answer
Angle between two objects' facing direction 2 Answers
How do i shoot in the direction im facing? 3 Answers
How to make a gameobject face the same direction the joystick is pointing to? 0 Answers