初学者的Unity球轨迹2D

大家好。本文将致力于编写Unity中球轨迹的预测。Unity版本2019.0.6f

我们将使用LineRenderer画一条线。

首先,准备LineRenderer:



需要更改的内容:

  1. 线的粗细
  2. 线色
  3. 材料

要以2D方式绘制LineRenderer,您需要使用“ Sprite / Default”着色器



创建材质:创建BallTrajectory脚本并定义必要的字段。

栏位定义
public class TrajectoryRenderer : MonoBehaviour
{
      [SerializeField] LineRenderer lineRenderer; //  LineRenderer
      [SerializeField] int lineCount; // ,  ,     
      [SerializeField] float lineLenght; // 
      [SerializeField] Ball ball; //   
}


首先,我们为LineRenderer设置所需的点数。

私人 void  Start
{
      lineRenderer positionCount  =  lineCount ;
}

将来,我们将在Update函数中编写代码。

首先,您需要确定鼠标在世界坐标系中当前帧中的位置,为此,我们将使用相机类的ScreenToWorldPoint方法。

Vector2 mousePos  =  相机主要ScreenToWorldPoint 输入MousePosition ;

之后,您需要找到来自球中心并指向鼠标位置的法线向量。
Vector2方向  =  mousePos结构  -   Vector2 变换位置;
方向规范化;

接下来,您需要确定球速度的垂直和水平分量。

创建一个球类。在其中,我们确定其速度,然后通过按鼠标右键将球以给定速度朝着鼠标位置发射。

球剧本
public class Ball : MonoBehaviour
{
    Rigidbody2D rb;
    [SerializeField] float velocityScaler;
    public float velocity;
 
    Vector2 mousePos;
 
    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }
 
    private void Update()
    {
        mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        velocity = Vector2.Distance(transform.position, mousePos) * velocityScaler;
 
        if (Input.GetMouseButtonUp(0))
        {
            Vector2 direction = (mousePos - (Vector2)rb.transform.position);
            direction.Normalize();
            rb.velocity = direction * velocity;
        }
    }
}


球速测定
var vx = ball.velocity * direction.x;
var vy = ball.velocity * direction.y;


最后,我们需要遍历LineRenderer的所有点,并根据接收到的数据确定它们的位置。

点定位
for (int i = 0; i < lineCount; i++)
{
      float t = i * lineLenght;
      var nextPos = new Vector2(vx * t, vy * t - (-Physics2D.gravity.y * t*t) / 2);
      lineRenderer.SetPosition(i, (Vector2)transform.position + nextPos);
}


完整的代码可以查看

这里
public class BallTrajectory : MonoBehaviour
{
      [SerializeField] LineRenderer lineRenderer;
      [SerializeField] int lineCount;
      [SerializeField] float lineLenght;
      Ball ball;
 
      private void Start()
      {
            ball = GetComponent<BallController>();
            lineRenderer.positionCount = lineCount;
      }
 
      private void Update()
      {
            Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            Vector2 direction = mousePos - (Vector2)transform.position;
            direction.Normalize();
 
            var vx = ball.velocity * direction.x;
            var vy = ball.velocity * direction.y;
 
            for (int i = 0; i < lineCount; i++)
            {
                  float t = i * 0.1f;
                  var nextPos = new Vector2(vx * t, vy * t - (-Physics2D.gravity.y * t*t) / 2);
                  lineRenderer.SetPosition(i, (Vector2)transform.position + nextPos);
            }
      }
 
}


屏幕截图



谢谢你的狂欢

All Articles