ObjectiveIn this Sample code you can see how to Hit Target Using Ballistic Trajectory.
Step 1 Basic Info
- Get Fire Direction
- Get Height Difference
- Get Horizontal Distance Using direction.megnitude
- Convert Degree Angle To Radians
- Set Direction To Evolution Angle
- Correct Small Height Difference i.e distance = distance + h / tan(angle)
- Calculate Velocity Sqrt(dista * grevity.magnitude / sin(2 * angle))
- Normalize Direction Velocity * Direction.normalize
Step 2 Code Sample
var dir = target.position - transform.position; // get target direction var h = dir.y; // get height difference dir.y = 0; // retain only the horizontal direction var dist = dir.magnitude ; // get horizontal distance var a = angle * Mathf.Deg2Rad; // convert angle to radians dir.y = dist * Mathf.Tan(a); // set dir to the elevation angle dist += h / Mathf.Tan(a); // correct for small height differences // calculate the velocity magnitude var vel = Mathf.Sqrt(dist * Physics.gravity.magnitude / Mathf.Sin(2 * a)); vel = vel * dir.normalized;
I hope you found this blog helpful while Hit Target Using Ballistic Trajectory. Let me know if you have any questions or concerns regarding Unity please put a comment here and we will get back to you ASAP.
An entrepreneur who has founded 2 flourishing software firms in 7 years, Tejas is keen to understand everything about gaming - from the business dynamics to awesome designs to gamer psychology. As the founder-CEO of a company that has released some very successful games, he knows a thing or two about gaming. He shares his knowledge through blogs and talks that he gets invited to.