Question by
Whelandrew · Jul 31, 2020 at 05:02 PM ·
physicstrajectory
Projectile Trajectory Precision
I wrote a script to calculate the trajectory of an arrow firing from the player. I have a gameobject, as a child inside the player, to indicate where the missile fires from. I get it's destination with Camera.main.ScreenToWorldPoint(Input.mousePosition).
Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition);
utilities.SetTrajectoryPoints(trajectoryDotsCache.transform.position, direction, trajectoryDots.ToArray());
Then, I call a Trajectory Calculator and it takes the origin and destination positions and draws a sequence of green dots to draw the path from A to B.
public Vector2 SetTrajectoryPoints(Vector2 posStart, Vector2 direction, Transform[] trajectoryDots)
{
//Debug.Log(direction.y);
//float magX = (posStart - direction).magnitude * ((direction.x > 0) ? 1 : -1);
//float magY = magX * ((direction.y > 0) ? 1 : -1);
float finalX = direction.x;
float finalY = direction.y;
//Velocity(u) = Mathf. Sqrt((x * x) + (y * y));
float velocity = Mathf.Sqrt((finalX * finalX) + (finalY * finalY));
//Angle = Mathf.Atan2(y, x);
float angle = Mathf.Rad2Deg * (Mathf.Atan2(finalY, finalX));
float tTime = .1f;
Vector2 pos = Vector2.zero;
for(int i=0;i<10;i++)
{
float dx = velocity * tTime * Mathf.Cos(angle * Mathf.Deg2Rad);
float dy = velocity * tTime * Mathf.Sin(angle * Mathf.Deg2Rad) + (Physics2D.gravity.magnitude * tTime * tTime / 2f);
pos = new Vector2(posStart.x - dx, posStart.y - dy);
if (trajectoryDots != null)
{
Transform dot = trajectoryDots[i];
dot.position = pos;
dot.gameObject.SetActive(true);
dot.eulerAngles = new Vector3(0, 0, Mathf.Atan2(finalY - (Physics.gravity.magnitude) * tTime, finalX) * Mathf.Rad2Deg);
}
tTime += .1f;
//Debug.Log(pos);
}
return pos;
}
In the example below, note the green dots stretch off into the distance. What I want is for the calculated arch to reach where the red mark is located in the picture (this is an indication of where the mouse click happened).
capture.png
(347.2 kB)
Comment