- Home /
Add rotation to rigidbody AddForce?
I am using input from the player
accel = Input.GetAxis ("Vertical") ;
to move a sphere rigidbody using
rigidbody.AddForce
I would like to use the input
turn = Input.GetAxis ("Horizontal") ;
To turn the sphere. In other words, I would like to adjust the the Quaternion of the shpere so that the forward momentum generated by rigidbody.AddForce changes direction one degree + or - as the player is pressing left, right arrows
All of my attempts result in the shpere turning, but not changing the forward momentum direction. Any ideas how to do this?
Answer by Tabu · Aug 08, 2010 at 01:11 PM
EDIT: Saw you wanted to use AddForce, Im not sure, but I guess this same principel should work with that also. BTW: This is done in C#
Tried to make a quick example, I think this should do the trick, Fiddle about with it, to get it to fit what your trying to do.
using UnityEngine;
using System.Collections;
public class testMovementScript : MonoBehaviour {
public Rigidbody theBody; public float moveSpeed; public float rotation; private Vector3 moveDirection;
// Use this for initialization void Start () {
}
// Update is called once per frame void Update () { transform.Rotate(Input.GetAxis("Horizontal") rotation Time.deltaTime, 0, Input.GetAxis("Horizontal") -rotation Time.deltaTime); //This is where you rotate your GameObject.
//This is where you move the GameObject about.
moveDirection = new Vector3(0, 0, moveSpeed * Input.GetAxis("Vertical"));
theBody.transform.Translate(moveDirection);
}
}
Yes, this is exactly want I meant. I had suspected that it was by somehow using the translation conponent of the object. Very helpful!
Answer by StephanK · May 27, 2010 at 02:14 PM
I'm not sure if I understood what you want to do. If you want a force that points into another direction all you have to do is rotate the force before you add it. If you want to change the direction of the momentum the sphere already has you will have to rotate the spheres rigidbody.velocity accordingly.
Answer by spinaljack · May 27, 2010 at 02:15 PM
You need to track the forward direction yourself as a variable and apply a constant force in that direction to maintain movement in the correct direction. Use a highish drag value to prevent the ball from picking up speed over time. When you press the left and right keys rotate the forward direction and apply a force relative to the forward direction.
Placing the sphere in a container game object will help you with keeping the correct forward direction.
It's a bit of a round about way but movement like you describe isn't very realistic.