1

I am trying to implement a function in my game which will auto-lock a target and throw a projectile so that it lands perfectly on it. I did the maths to calculate a parabola from Player 1 -> Target wherever their positions are but realised I wanted to use Unity's physics system rather than having the ball follow a path.

The throw velocity is constant, Player 1 and Target are moving objects but their positions will be registered once only to calculate the initial angle of the throw.

I believe this is the formula I need to use: enter image description here

But how can I apply it for my Player and Target both having 3D coordinates?

Here is the pseudo-code of what I tried to write in Unity to make more easily readable.

float velocity = 100f; 
float g = Physics.gravity;
Transform x = Target.position.x - Player.position.x;
Transform y = Target.position.z - Player.position.z;
double theta;

theta = **big formula using the values above**

And after that I do not know how to use this value to add force to the projectile. I wanted to use AddForce(x,y,z, ForceMode.Impulse); but I clearly cannot use an initial angle here, only an x and y value. Using RigidBody.velocity = Vector3(vx, vy, vz); gives me the same problem.

I believe I am missing something trivial but I really am stuck on this. Would anyone be able to help?

SecureCake
  • 170
  • 1
  • 8
  • 1
    If you take the argument of the `arctan` function, a vector with the numerator as its y-component and the denominator as its x component has the required direction. It just needs to be scaled to have the correct magnitude / velocity. – Nico Schertler Feb 24 '19 at 03:56
  • This means that scaling this vector would simply require me to multiply each value by the float velocity since the angle was calculated with it? Since Theta is a float in Radians, how may I compute its numerator and denominator? I have a bit of trouble with complex numbers and even more manipulating them with .NET libraries. – SecureCake Feb 24 '19 at 05:34
  • 1
    I mean the stuff in your formula (`v² +- sqrt(…)` for the numerator and `gx` for the denominator). You need to normalize the vector and multiply it by the velocity. Unity should have methods that do this for you. – Nico Schertler Feb 24 '19 at 05:42
  • Thank you! The ball is now thrown in the correct direction every time, although the vector values are not scaling correctly I believe. With a defined constant initial velocity, the Y value of the throw vector is not strong enough to reach the target from various coordinates around it. I will try to figure this out on my own, thank you for the help! – SecureCake Feb 24 '19 at 14:56
  • Unity might have some non-conforming physics models. Not sure. Make sure that the gravity you use is the same that Unity is using. – Nico Schertler Feb 24 '19 at 17:48

0 Answers0