在Unity中,实现两点生成抛物线,物体在生成的抛物线上移动的效果。

  1. 创建游戏物体:编写脚本,将游戏物体放置在抛物线上,让游戏物体沿抛物线移动。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ParabolaMovement : MonoBehaviour
{
    public GameObject startPoint;
    public GameObject endPoint;
    public float speed;
    private float t;
    private bool moving;

    void Update()
    {
        if (moving)
        {
            t += Time.deltaTime * speed;
            if (t >= 1f)
            {
                t = 1f;
                moving = false;
            }
            Move();
        }
    }

    public void MoveOnParabola()
    {
        moving = true;
        t = 0f;
    }

    void Move()
    {
        Vector3 position = CalculateParabola(startPoint.transform.position, endPoint.transform.position, t);
        transform.position = position;
    }

    Vector3 CalculateParabola(Vector3 start, Vector3 end, float t)
    {
        Vector3 height = Vector3.up * (end - start).magnitude * 0.3f;
        Vector3 midPoint = (start + end) * 0.5f + height;

        Vector3 P0 = start;
        Vector3 P1 = midPoint;
        Vector3 P2 = end;
        float u = 1 - t;
        float tt = t * t;
        float uu = u * u;
        Vector3 p = uu * P0;
        p += 2 * u * t * P1;
        p += tt * P2;
        return p;
    }
}
  1. 创建抛物线:使用Line Renderer绘制抛物线,可以使用上面编写的CalculateParabola函数来计算抛物线上的每一个点,然后将其添加到Line Renderer中。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ParabolaLine : MonoBehaviour
{
    public GameObject startPoint;
    public GameObject endPoint;
    public int lineSegmentNum;

    private LineRenderer lineRenderer;

    void Start()
    {
        lineRenderer = GetComponent<LineRenderer>();
        lineRenderer.positionCount = lineSegmentNum;
        DrawParabola();
    }

    void DrawParabola()
    {
        Vector3 start = startPoint.transform.position;
        Vector3 end = endPoint.transform.position;
        float step = 1f / lineSegmentNum;

        for (int i = 1; i <= lineSegmentNum; i++)
        {
            float t = step * i;
            Vector3 position = CalculateParabola(start, end, t);
            lineRenderer.SetPosition(i - 1, position);
        }
    }

    Vector3 CalculateParabola(Vector3 start, Vector3 end, float t)
    {
        Vector3 height = Vector3.up * (end - start).magnitude * 0.3f;
        Vector3 midPoint = (start + end) * 0.5f + height;

        Vector3 P0 = start;
        Vector3 P1 = midPoint;
        Vector3 P2 = end;
        float u = 1 - t;
        float tt = t * t;
        float uu = u * u;
        Vector3 p = uu * P0;
        p += 2 * u * t * P1;
        p += tt * P2;
        return p;
    }
}

在这里插入图片描述

如果物体没有沿着抛物线移动
1.检查物体是否添加了脚本ParabolaMovement
2.检查脚本中的变量startPoint、endPoint是否被正确赋值
3.检查脚本中的MoveOnParabola()函数是否被调用