1. 程式人生 > >Unity 3d讓物體成弧線運動(可以製作炮彈發射的軌跡)

Unity 3d讓物體成弧線運動(可以製作炮彈發射的軌跡)

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;
        }
    }


}