I have a gameObject that is rotated by pressing the a and d keys moved and moved by pressing the right mouse button (adding a relative force to the rigidbody).
I use the following code:
void Update()
{
float rot = Input.GetAxis("Horizontal") * rotationSpeed * Time.deltaTime;
transform.Rotate(0, rot, 0);
}
void FixedUpdate()
{
if (Input.GetButton("Fire2"))
{
rigidbody.AddRelativeForce(0, 0, forwardSpeed * Time.deltaTime);
}
}
This works, well, almost!
If the object is only rotated a few degrees, the object does not move forward when a applied a force to it. It's like it rounds the angle of the force to the nearest 10 degrees or so.
In a test, where a added a lot of force to the object on RMB, it looked like it worked fine.
What am I doing wrong? How can I add more precision to the direction of the force.
Well, first of all - you shouldn't usually mix physics and direct transformations...
From the Unity Manual:
To control your Rigidbodies, you will
primarily use scripts to add forces or
torque. You do this by calling
AddForce() and AddTorque() on the
object's Rigidbody. Remember that you
shouldn't be directly altering the
object's Transform when you are using
physics.
So either you go the physics way and translate and rotate it using RigidBody.AddForce() and RigidBody.AddTorque()
or - rotate using Transform.Rotate(), and move using Transform.Translate(). Just try and not mix and match, since the results won't be predictable.
Also check out the meaning of a kinematic RigidBody in the docs. Maybe it will let you understand the whole thing better.
If you don't need physics (And trust me when I say - most times you don't), try looking at the different character controllers on both the wiki and the standard assets to see how to play around with acceleration, relative vectors and "fake" physics using only the Transform component. I usually avoid using physics for controllers unless it's absolutely necessary or right for the specific project.
Checking "Freeze Rotation" on the rigid body solved my problem.
Duck writes in this answer :
Because your cube is actually scraping along the ground (unless you've turned off gravity), it may be that at certain times during its motion, your cube is actually in contact with the ground with fewer than all 4 of its bottom points. If this occurs, the friction against the ground may asymmetrical and cause your object to move in a direction other than its forward direction.
Checking Freeze Rotation prevents the force from rotating the collider (a box collider) from changing the contact with the ground surface - at least that is my best guess to why it works.
Ofcourse, if you need the physics rotation, this will not help.