- Home /
Weird issue with fire angle of projectiles changing
So, I have a tank, and this tank spawns a projectile, applying force to fire it forward with an upward angle. I am using the following code to accomplish this:
// fire the projectile applying our force and angle
var proj : GameObject = GameObject.Instantiate(projectile,
transform.position + (transform.forward * 15),
transform.rotation);
proj.rigidbody.AddForce((Quaternion.Euler(angle,0,0) * transform.forward) * 10000);
Let's assume the angle is 45 (which is what I test with). This code works to a point, but the issue I am having is that as I rotate my tank around its Y axis, the upward angle goes from positive to negative.
Imagine the way Pluto orbits our sun, how it is lower at some points relative to the sun, and higher at others. The angle of the projectiles appear to be changing like this.
So, if I fire in one direction, it fires at a 45 degree angle, if I rotate 90 degrees, it fires at a 0 degree angle. another 90 degrees and it is at a -45 degree angle, etc.
My question is: How do I maintain a positive, 45 upward degree angle, relative to the forward position of the tank, regardless of its rotation around its Y axis?
Answer by Wolfram · Jun 04, 2012 at 09:37 PM
"Quaternion.Euler(angle,0,0)" always refers to the world-X-axis, but you need the local orientation of your tank. This should work:
proj.rigidbody.AddForce((transform.rotation * Quaternion.Euler(angle,0,0) * transform.forward) * 10000);
Or another alternative:
proj.rigidbody.AddForce((Quaternion.Euler(transform.InverseTransformDirection(angle,0,0)) * transform.forward) * 10000);
(this is off the top of my head, so I hope I got it both right...)
Hm, thinking about it, you might need to replace "transform.forward" with "Vector3.forward"...and now I have a knot in my brain...best try all 4 alternatives ;-)
proj.rigidbody.AddForce((transform.rotation Quaternion.Euler(-angle,0,0) Vector3.forward) * 10000); Did the trick. Thank you so much! Was driving me nuts.