- Home /
Calculate direction thrown projectile (rigidbody) (Js)
Hi, i need help with a simple AI... I need my enemy to throw a GameObject against my player...but i need the gameobject to do like in reality: i mean, if i need to throw a ball against something, i have to calculate the direction and the force to put into the ball to hit the target. How can i say this to a script? My ball (the projectile) has a rigidbody, so i guess i need to calculate the velocity etc...how can i do this? Thank you a lot!
Answer by koray1396 · Apr 25, 2014 at 07:22 PM
way 1: you should go backwards. say if you throw something with an angle of a and with a velocity of v, it will go for a distance of d.
the equation would be something like this,
(cosa)(2 v * sina) / (gravity) = d
one approach would be fixing the velocity, and finding the angle;
cosa sina = (d gravity) / (2 * v)
sin2a = 2 (d gravity) / (2 * v)
a = arcsin(2 (d gravity) / (2 * v)) / 2
hope there is no mistake in the above, but this would be the general idea.
and you would know that the object would travel max. if it's thrown at 45 degrees. So, before above, you would calculate distance with fixed velocity and 45 degree angle, if it's lower than required, you would find the velocity with 45 degrees.
another way:
in lastupdate, try some angles and velocities and iterate them for a solution, then apply them for real in the next update.
last way:
store some values for angle and velocity (or force) after testing, and use them when needed.
no code provided, but I'm sure you can figure out from here.
Answer by Cherno · Apr 26, 2014 at 02:36 AM
See this thread:
Calculate force applied to rigidbody to make it land at specific location
Specifically, the link in Aldonaletto's answer:
Your answer
![](https://koobas.hobune.stream/wayback/20220613143557im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
NavMesh flee. Ai flee from player. 4 Answers
Rigidbody movement 1 Answer
player to kill ai 0 Answers
Attach a Player to a moving GameObject 0 Answers
Parent Object 0 Answers