I have this code which simulates a projectile motion, it works well till I am just looking for prediction from just start position but when I try to Calculate the path after collision, I seem to have an issue, it will be great if someone can check my code and see what I am doing wrong here,
The method OnThrow is called in Update() where I just pass in a startTransform.
private void OnThrow(Transform t)
{
lr.positionCount = 0;
List<Vector3> positions = new List<Vector3>();
InitialPos = t.transform.position;
float angle = m_Angle;
for (float i = 0; i < 3; i += Time.fixedDeltaTime)
{
float x = InitialPos.x + m_Force * Mathf.Cos(angle * Mathf.Deg2Rad) * i;
float y = InitialPos.y + m_Force * Mathf.Sin(angle * Mathf.Deg2Rad) * i + 0.5f * -9.8f * i * i;
Vector2 pos = new Vector2(x, y);
positions.Add(pos);
int count = Physics2D.OverlapCircleNonAlloc(pos, 0.1f, colliders);
if (count > 0)
{
int length = positions.Count > 2 ? positions.Count - 2 : positions.Count - 1;
Vector2 dir = (pos - (Vector2)(positions[length])).normalized;
RaycastHit2D hit = (Physics2D.Raycast(pos, dir, 0.1f)) ;
if(hit.collider!= null)
{
Vector2 reflect = Vector2.Reflect(dir, hit.normal);
Debug.DrawRay(hit.point, dir, Color.black, 1);
Debug.DrawRay(hit.point, reflect, Color.red, 1);
float newAngle = Mathf.Atan2(reflect.y, reflect.x) * Mathf.Rad2Deg;
angle = newAngle;
positions.Add(hit.point + reflect * 1f);
InitialPos = hit.point + reflect * 1f;
}
}
}
lr.positionCount = positions.Count;
lr.SetPositions(positions.ToArray());
}
It should be following the red line but I am doing something wrong.
Thanks for reading.