- Home /
CharacterController velocity problem
Hi,
I have a problem registering CharacterController X and Z velocities – they always stays at 0.
This is my script attached to the character:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(CharacterController))]
[RequireComponent(typeof(Animation))]
public class scr_controller : MonoBehaviour {
private CharacterController controller;
private Animation animations;
void Awake() {
controller = GetComponent<CharacterController>();
animations = GetComponent<Animation>();
}
void Update () {
if (Input.GetAxis("Horizontal") > 0) transform.Rotate(0,100 * Time.deltaTime,0);
if (Input.GetAxis("Horizontal") < 0) transform.Rotate(0,-100 * Time.deltaTime,0);
if (Input.GetAxis("Vertical") > 0) controller.Move(transform.TransformDirection(Vector3.forward) * Time.deltaTime * 3);
if (Input.GetAxis("Vertical") < 0) controller.Move(transform.TransformDirection(Vector3.back) * Time.deltaTime * 3);
controller.Move(Vector3.down * Time.deltaTime * 9.8f);
if (controller.velocity.magnitude == 0) animations.CrossFade("idle");
else animations.CrossFade("walk");
print(controller.velocity);
}
}
So, when I move him, controller.velocity keeps returning a zero vector. However, if my characters falls from somewhere Y velocity seems to react appropriately.
I’m really confused with that problem. Would appreciate any help. Thanks!
Answer by MountDoomTeam · Nov 18, 2012 at 09:19 AM
it looks like you're calling the velocity on a component called charactercontroller, and you have to call it the object the charactercontroller is attached to.the velocity function has to be on a rigid body. So print(GameObject.rigidbody.velocity), something like that
But I don't use a rigidbody component there... The say (http://docs.unity3d.com/Documentation/ScriptReference/CharacterController-velocity.html) that it should return "the difference in distance for the current timestep before and after a call to CharacterController.$$anonymous$$ove or CharacterController.Simple$$anonymous$$ove".
controller.$$anonymous$$ove(Vector3.down Time.deltaTime 9.8f);
that line only moves over Y axis, and it seems that you are reseting previous calls to $$anonymous$$ove
... if (Input.GetAxis("Vertical") > 0) controller.$$anonymous$$ove(transform.TransformDirection(Vector3.forward) Time.deltaTime 3); if (Input.GetAxis("Vertical") < 0) controller.$$anonymous$$ove(transform.TransformDirection(Vector3.back) Time.deltaTime 3); ...
Create only one movement vector and call $$anonymous$$ove one time per update