- Home /
Having trouble turning a Transform movement into a Rigidbody force. Code included
I'm trying to create Arwing-like controls, in that my player is always moving forward relative to its rotation, and it can be rotate along any axis (Yaw, pitch, roll).
I have tried applying a rigidbody and converting my code (See the verbose commented out lines for my failures) yet, weird stuff would happen, like moving along the wrong axis, having to rotate things in my prefab to appropriate for inverted axis, crazy jazz. I really, really need collisions to happen though.
Here is my code:
//rb.AddRelativeForce(Vector3.up * (speed + boostHolder));
//rb.MovePosition(Vector3.forward * (speed + boostHolder));
transform.Translate(forward * (speed + boostHolder));
transform.Rotate(Input.GetAxis("Vertical")* turnspeed, Input.GetAxis("Horizontal") * turnspeed, ((Input.GetAxis("Horizontal") / 3) * -1) + Input.GetAxis("Roll") * -turnspeed);
//rb.AddTorque (Input.GetAxis("Vertical") * turnspeed, Input.GetAxis("Horizontal") * -turnspeed,0);
//transform.Rotate(vfloat * turnspeed, Input.GetAxis("Horizontal") * turnspeed, ((Input.GetAxis("Horizontal") / 3) * -1) + Input.GetAxis("Roll") * -turnspeed);
Answer by Scoutas · Jan 11, 2017 at 09:07 PM
The moving on a wrong axis happens, because Translate
method of a tranform, moves the object in the Local Space
of the object. So passing in Vector3.forward
would move the object on it's forward axis. MovePosition
from the rigidbody, the documentation says that you pass in the position you want your object to move to, using smoothing. I'd suggest using AddForce
method, if you want to calculate the direction in the World Space of where the object has to go yourself, of AddRelativeForce
if you want to just use Vector3.forward
and make the object go on it's forward axis.
Same thing would happen with the addition of torque, but I myself have not played around with it too much, so I don't want to say something that's completely wrong.
Thank you, it's helpful.
I've completely rewritten my player movement and AI scripts to use rigidbodies ins$$anonymous$$d of directly translating the transform. Now they bounce off of the terrain, which is all I wanted, really.
But now the AI rotates like it is supposed to, but doesn't face the direction of movement / vice versa (Seems to have so much momentum / inertia that when it rotates or decides on new rotations / paths / targets, it just keeps traveling in the direction of that momentum -- even though it is applying forward force relative to its own rotation every frame.