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!

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.

See this thread:

Calculate force applied to rigidbody to make it land at specific location

Specifically, the link in Aldonaletto’s answer:

Shooting a cannonball.