- Home /
Character Controller - unknown rotation, flying
I have a character. I have two seperate scripts for movement and looking around. I am using character controller.
First script makes the head move around as you look (camera is attached to the head) which means that only the head moves. Body rotates after the head has reached the shoulders... to prevent the head going all around.
Second script is meant for player movement. I want the player to move in the direction the CAMERA IS FACING - not the direction that the body is facing. I am using the following code:
public class MovementScript : MonoBehaviour {
public float speed = 5.0f;
public float jumpVelocity = 240.0f;
CharacterController cc;
void Start()
{
cc = GetComponent<CharacterController>();
}
void Update(){
GameObject cm = GameObject.Find("camera_001");
Vector3 direction = cm.transform.TransformDirection(Vector3.forward) * speed;
Vector3 forward = Input.GetAxis("Vertical") * direction;
cc.Move(forward * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.Space) && cc.isGrounded)
{
gameObject.rigidbody.AddForce(Vector3.up * jumpVelocity);
}
}
}
1.problem --> the body starts spinning around nonstop after some walking around. I can't seem to find the problem that is causing this rotation.
2.problem --> the direction is Vector3 - because of that - when looking down and moving backwards the player will fly up. (Or vice versa - looking up and going forward...). I know the problem but have no idea how to fix it.
If anyone has a better idea of doing this, please tell me.
Help would be greatly appreciated. Thanks.
Answer by AlejandroGorgal · Nov 30, 2013 at 07:27 PM
Judging by your code, it seems like you have a rigidbody on your character, you can't have one of those AND a character controller at the same time, Unity's not going to like that and it's likely the reason why you are having these problems.
My advice would be to get rid of the character controller and stick to a rigidbody + capsule collider for simplicity.
I removed the controller. Now I am using only the rigidbody and a box collider that I already created. The problem now becomes the code. What should I use for movement?
Ok, for problem 1 you should go to the rigidbody component and freeze rotation in all 3 axis, I think that should solve that.
For the second issue, look at this documentation regarding rigidbodies in first person games:
and:
http://wiki.unity3d.com/index.php?title=RigidbodyFPSWalker
I hope that helps, good luck!