Hello. Sorry for my bad English. I’m making 2d game and I need to realize projectile motion in it. I wrote this code to make it work:
private float angle;
private float velocity;
private float g = 9.80665f;
private float t;
private float flightTime;
void Start()
{
// scale object
var scale = CameraSetter.YMax * 2 / 4;
transform.localScale = new Vector3(scale, scale, 0);
//set desirable parameters for projectile motion
t = 0;
var maxHeight = CameraSetter.YMax + CameraSetter.YMax/2;
var range = CameraSetter.XMax*2;
angle = CalculateAngle(maxHeight, range);
velocity = CalculateVelocity(range);
flightTime = CalculateFlightTime();
}
private float CalculateFlightTime()
{
return (2*velocity*Mathf.Sin(angle*Mathf.Deg2Rad))/g;
}
private float CalculateVelocity(float range)
{
return Mathf.Sqrt((range * g) / Mathf.Sin(angle * 2 * Mathf.Deg2Rad));
}
private float CalculateAngle(float maxHeight, float range)
{
return Mathf.Atan(4*maxHeight/range)*Mathf.Rad2Deg;
}
void Update()
{
t += Time.deltaTime;
var x = GetXv();
var y = GetYv();
transform.position = new Vector3(x, y, 0);
}
private float GetYv()
{
return ((velocity * t * Mathf.Sin(angle * Mathf.Deg2Rad)) - 0.5f * (g * (t * t))) - CameraSetter.YMax;
}
private float GetXv()
{
return (velocity * t * Mathf.Cos(angle * Mathf.Deg2Rad)) - CameraSetter.XMax;
}
This works fine to me: object starts moving from left bottom corner to right bottom corner with parabolic trajectory and maximum height in center (with coordinates x=0, y=orthographicSize/2). However, it’s moving not smoothly, so i decided to do Lerp like this:
transform.position = Vector3.Lerp(transform.position, new Vector3(x, y, 0), Time.deltaTime);
instead of
transform.position = new Vector3(x, y, 0);
and this actually ruined the whole thing!! Trajectory now ends in somewhere near the center bottom with max height just about y=-orthographicSize/3 or something like that.
Please explain me why Lerp is ruining trajectory and how can i fix it (i need working trajectory with smooth movement).