I have a cannon (the source) point, the projectile (a cannonball) and a target. How do I call the cannonball’s rigidbody so it lands exactly on the target? I want the trajectory to be an arc shape. This is in 3D space (that is, it’s not a 2D platformer like all the other similar questions seem to be asking about).
2 Answers
2First of all, if you want to spend money and exert minimum effort the free iTween package for Unity has an example project that does pretty much exactly what you’re looking for ( iTween for Unity by Bob Berkebile (pixelplacement) ). The package of examples costs $20, so you may not want to go that route.
If you wanted to do it numerically / with realistic physics, you’d have to solve a few of basic physics equations. You have two variables that describe the motion: the initial velocity and the firing angle. Wikipedia has a great section on the parabolic equation you would need:
In a nutshell, you plug in your desired velocity or angle and range to get the required angle or velocity to hit your target. Then, turn on gravity for the rigidbody and set the initial velocity of the rigidbody. Assuming we’re firing in the positive X direction:
rigidbody.velocity = new Vector3(desiredVel * Mathf.Cos(desiredAngle), desiredVel * Mathf.Sin(desiredAngle), 0f);
In any other direction the Y velocity is the same and you change the X and Z trigonometrically based on your angle around the Y axis.
If you wanted friction from the air this becomes a differential equation, and you should consult your local mathematician.
BTW: just so we're clear, the case is exactly the same as for all the other 2D platformer game examples you mention, except that in those examples we assume that we're firing in the positive X direction. For an angle from positive X of theta, the amount of velocity in X and Z changes by: X = origVal * Cos(theta) Z = origVal * Sin(theta) Once you fire off the projectile, you don't have to do any other math, as Unity will apply gravity for you.
– Julien-LyngeI answered a similar question some time ago - the cannon shoot at 45 degrees and the ball always land on the target position (unless the target runs away before). Clike here to read this answer.
I'm looking for a way to make the same but with variable angles (from 30 to 80 degrees) any suggestions? Thanks in advance for your time!
– neroziros
You have to do your own physics calculations. There is no exposed Unity functionality for that. I suggest you implement the case without drag.
– Waz