using UnityEngine;
public class ProjectileMotion : MonoBehaviour
{
//投掷物
[SerializeField] private GameObject bomb;
//力
[SerializeField] private float force;
[SerializeField] LineRenderer lineRenderer;
private float theta;
//速度
private float velocity;
Vector3[] ves;
private void Start()
{
lineRenderer.positionCount = 100;
ves = new Vector3[100];
}
Vector2 dir;
private void Update()
{
//弧度
float yLength = Camera.main.ScreenToWorldPoint(Input.mousePosition).y - transform.position.y;
float xLength = Camera.main.ScreenToWorldPoint(Input.mousePosition).x - transform.position.x;
//返回其切线为两个浮点数的商的角度。
theta = Mathf.Atan2(yLength, xLength);
dir = ((Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition) - (Vector2)transform.position).normalized;
//速度
velocity = (dir * force).magnitude;
if (Input.GetKeyDown(KeyCode.J))
{
GameObject Projectile = Instantiate<GameObject>(bomb, transform.position, Quaternion.identity);
Projectile.GetComponent<Rigidbody2D>().velocity = dir * force;
}
for (int i = 0; i < 100; i++)
{
float t = i * 0.05f;
float x = velocity * t * Mathf.Cos(theta) + transform.position.x;
float y = velocity * t * Mathf.Sin(theta) + 0.5f * Physics2D.gravity.y * t * t + transform.position.y;
ves[i] = new Vector3(x, y, 0);
}
lineRenderer.SetPositions(ves);
}
}