- Home /
Character Rotate Properly
With this script, I can move and rotate my character.
Rigidbody rb;
public float speed = 6.0F;
public float forwardSpeed;
public float turnSpeed;
private Vector3 moveDirection = Vector3.zero;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody> ();
}
// Update is called once per frame
void FixedUpdate () {
rb.AddRelativeForce(0, 0, forwardSpeed * 100 * Time.deltaTime);
moveDirection = new Vector3(Input.GetAxis("Horizontal"), -Input.GetAxis("Vertical"), 0);
moveDirection = transform.TransformDirection(moveDirection);
rb.AddRelativeForce(moveDirection * speed * Time.deltaTime, ForceMode.VelocityChange);
transform.rotation = Quaternion.RotateTowards (transform.rotation, Quaternion.LookRotation (moveDirection), turnSpeed * Time.deltaTime);
}
However, I can rotate around in a circle and my rotation really doesn't follow my movement. It's kinda hard to explain. I'm trying to accomplish a moving system as in Mario Odyssey's Bullet Bill (https://www.youtube.com/watch?v=wuGWBjB3-Mo&feature=youtu.be&t=479)
Thanks so much for any help :)
Answer by Kwergan · Dec 06, 2017 at 02:13 AM
It seems that you are using the moveDirection as input for the rotation. This will rotate the character towards the direction of the controller input rather than the velocity, which is what I think you want. Try:
transform.rotation = Quaternion.RotateTowards (transform.rotation, Quaternion.LookRotation (rb.velocity), turnSpeed * Time.deltaTime);
Thanks for the answer! This is an improvement but my character starts to tremble when it rotates to a certain degree. $$anonymous$$aybe I should try a different approach altogether...:\
transform.rotation = Quaternion.RotateTowards (transform.rotation, Quaternion.LookRotation (rb.velocity), Vector3.Angle(rb.velocity, transform.forward) * turnSpeed * Time.deltaTime);
The Vector3.Angle uses the angle between forward and the desired direction as a factor of rotation. So the character should rotate faster the further they are from the target. You may have to tweak turnSpeed. @$$anonymous$$ergster
No luck....It stopped trembling(except if you hold down the up key for a long time) but this movement doesn't seem dynamic no matter what value I use for turnSpeed.
Answer by fdz_ · Dec 08, 2017 at 11:07 PM
is this any helpful? tutorial by N3K EN for Fly Control
Not really...It would be if the tutorial was about how to make that work with a Rigidbody. I already know how to do that with a Character Controller and I rather wanted to do this with a Rigidbody for collision detection and other things... Thanks anyway though. :)
What if you use the script from the dude, but you change the last line:
charController.$$anonymous$$ove(moveVector * Time.deltaTime)
to:
rb.velocity += moveVector * Time.deltaTime
or:
rb.AddForce( moveVector )