Unity 3d让物体成弧线运动(可以制作炮弹发射的轨迹)

using UnityEngine;
using System.Collections;

public class MoveCurve : MonoBehaviour {

    public GameObject t1;    //开始位置
    public GameObject t2;     //结束位置
  // Update is called once per frame
    void Update () {

        //两者中心点
        Vector3 center = (t1.transform .position + t2.transform.position) * 0.5f;

        center -= new Vector3(0, 1, 0);

        Vector3 start = t1.transform.position - center;
        Vector3 end = t2.transform.position - center;

        //弧形插值
        transform.position = Vector3.Slerp(start,end,Time.time);
        transform.position += center;
        
    }
}

 
 
 
还有一种方法也可以实现,代码如下

using UnityEngine;
using System.Collections;

public class ProjectileTest : MonoBehaviour
{
    public GameObject target;   //要到达的目标
    public float speed = 10;    //速度
    private float distanceToTarget;   //两者之间的距离
    private bool move = true;    

    void Start()
    {
        //计算两者之间的距离
        distanceToTarget = Vector3.Distance(this.transform.position, target.transform.position);  
        StartCoroutine(StartShoot());
    }

    IEnumerator StartShoot()
    {

        while (move)
        {
            Vector3 targetPos = target.transform.position;

            //让始终它朝着目标
            this.transform.LookAt(targetPos);

            //计算弧线中的夹角
            float angle = Mathf.Min(1, Vector3.Distance(this.transform.position, targetPos) / distanceToTarget) * 45;
            this.transform.rotation = this.transform.rotation * Quaternion.Euler(Mathf.Clamp(-angle, -42, 42), 0, 0);
            float currentDist = Vector3.Distance(this.transform.position, target.transform.position);
            if (currentDist < 0.5f)
                move = false;
            this.transform.Translate(Vector3.forward * Mathf.Min(speed * Time.deltaTime, currentDist));
            yield return null;
        }
    }


}

 
阅读更多
换一批

没有更多推荐了,返回首页