Quantcast
Channel: Latest Questions by Z0hann
Viewing all articles
Browse latest Browse all 40

Barrel rotation Y, not working well with rigidbody.

$
0
0
Basically I have a barrel with a rigidbody and a sphere collider attached to it. What I'd like to achieve is, when the barrel moves forward, it rotates around the Z axis as a barrel would in real life. That's easily achieved by wether a forward wheter a backward force. **BUT** the problem comes when I'd like to rotate it around the Y axis, so I can turn with it. I was trying to chang it's rotation by having a rotY variable, which I increase or decrease depending on which direction to turn, then I convert that into a Vector3 which then I convert to a Quaternion with EularAngles and lastly I change the transform's rotation. It rotates to left and right but then the rotation to the Z axis doesn't work.. I was also trying with **rigidbody.MoveRotation()** but couldn't really figure it out how should it work for me perfectly. Anyone knows the solution ? Here's my code: public class Movement : MonoBehaviour { private Rigidbody rb; public float forward, backward, rotY; public Vector3 rotation; // Use this for initialization void Start () { rb = GetComponent(); rotY = 90.0f; } // Update is called once per frame void Update () { //Moving with keys if (Input.GetKey(KeyCode.UpArrow)) { rb.AddForce(Vector3.forward * forward, ForceMode.Acceleration); } else if (Input.GetKey(KeyCode.DownArrow)) { rb.AddForce(Vector3.back * backward, ForceMode.Acceleration); } if (Input.GetKey(KeyCode.LeftArrow)) { rotY -= 1.0f; } else if (Input.GetKey(KeyCode.RightArrow)) { rotY += 1.0f; } if (rotY > 360.0f || rotY < -360.0f) { rotY = 0.0f; } rotation = new Vector3(rb.rotation.x, rb.rotation.y + rotY, rb.rotation.z); //Rotation rb.rotation = Quaternion.Euler(new Vector3(rb.rotation.x, rotation, rb.rotation.z)); } }

Viewing all articles
Browse latest Browse all 40

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>