So I posted this in UnityAnswers, but because of the mass of replies I though I should post it in the forums so there can actually be a discussion about it. I’m having problems controlling a sphere, I want to get it rolling when I use WASD so I used RigidBody with addforce and addtorque. But after setting it all up it gets into an uncontrollable spin it seems like. It doesn’t move anywhere it just spins and spins and spins. To get a better understanding of what I mean, try making an empty scene with a terrain and a sphere with a rigidbody with: 1 Mass, 1 Drag, 1 Angular Drag, and this code attached:
var target: Transform;
var damp: float = 0.2;
var distance: float = 50;
function Update(){
damp = Mathf.Clamp(damp, 0.01, 10); // clamps damping factor
var pCam = transform.position;
var pTarget = target.position;
var diff: Vector3 = pTarget - pCam; // diff = difference between positions
var dist = diff.magnitude; // dist = distance between them
if (Mathf.Abs(diff.y) < 0.7*distance){
diff.y = 0; // doesn't modify camera height unless angle > 45
}
if (dist>distance){ // if distance too big...
diff *= 1-distance/dist; // diff = position error
// move a FPS independent little step towards the ideal position
transform.position = pCam + diff * Time.deltaTime/damp;
}
transform.LookAt(pTarget);
}
You should get the same behaviour I did. Any help to get it rolling like a ball that is rolling, would be greatly appreciated.
Like I posted on your question on UA, your script works as intended as long as there are reasonable values for linear drag and angular drag. I tried it again just now just to be doubly sure, and it still works. Unless you’re not releasing the button/s pressed, it should work as expected.
You said to test it with 1 for both drag and angular drag, so I did. Even with 0.1, it works fine – it’ll take longer to stop moving, but it’ll eventually stop. I changed the input accessors used to GetKey(KeyCode.whatever-key) since I didn’t want to set up 4 new axes, but that’s irrelevant in this case.
The best thing I can tell you is that all of your computations are relative to the ball’s orientation. So if the ball’s upside down, left is right, and forward is backward.
You should be using the camera’s orientation…
var speed=20.0;
function FixedUpdate () {
var torque=Vector3(Input.GetAxisRaw("Vertical"), 0, -Input.GetAxisRaw("Horizontal"));
if(torque.magnitude > 0.0){
torque=Camera.main.transform.TransformDirection(torque);
rigidbody.angularVelocity=Vector3.Lerp(rigidbody.angularVelocity, torque * speed, 0.3);
}
}