I'm digging in unity tutorial "3DGameKit". when a game monster shot a grenade, call the function GetVelocity() to set rigid body's velocity. In order to figure out this function,I studied Bezier curves and parabolic motion, I think it is more like parabolic motion,I know that in order to improve performance, the square may be directly used to participate in the calculation,but the relevant code does not seem to be related to the formula. I am sure I should be missing something important,the code is below, and the variable “projectileSpeed” is a float:
private Vector3 GetVelocity(Vector3 target)
{
Vector3 velocity = Vector3.zero;
Vector3 toTarget = target - transform.position;
// Set up the terms we need to solve the quadratic equations.
float gSquared = Physics.gravity.sqrMagnitude;
float b = projectileSpeed * projectileSpeed + Vector3.Dot(toTarget, Physics.gravity);
float discriminant = b * b - gSquared * toTarget.sqrMagnitude;
// Check whether the target is reachable at max speed or less.
if (discriminant < 0)
{
// Debug.Log("Can't reach");
velocity = toTarget;
velocity.y = 0;
velocity.Normalize();
velocity.y = 0.7f;
Debug.DrawRay(transform.position, velocity * 3.0f, Color.blue);
velocity *= projectileSpeed;
return velocity;
}
float discRoot = Mathf.Sqrt(discriminant);
// Highest shot with the given max speed:
float T_max = Mathf.Sqrt((b + discRoot) * 2f / gSquared);
// Most direct shot with the given max speed:
float T_min = Mathf.Sqrt((b - discRoot) * 2f / gSquared);
// Lowest-speed arc available:
float T_lowEnergy = Mathf.Sqrt(Mathf.Sqrt(toTarget.sqrMagnitude * 4f / gSquared));
float T = 0;
// choose T_max, T_min, or some T in-between like T_lowEnergy
switch (shotType)
{
case ShotType.HIGHEST_SHOT:
T = T_max;
break;
case ShotType.LOWEST_SPEED:
T = T_lowEnergy;
break;
case ShotType.MOST_DIRECT:
T = T_min;
break;
default:
break;
}
// Convert from time-to-hit to a launch velocity:
velocity = toTarget / T - Physics.gravity * T / 2f;
return velocity;
}
it works fine in my demo. I will very appreciate if somebody can explain that.