本文主要是介绍Unity 3d让物体成弧线运动(可以制作炮弹发射的轨迹),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
using UnityEngine;
using System.Collections;public class MoveCurve : MonoBehaviour {public GameObject t1; //开始位置public GameObject t2; //结束位置// Update is called once per framevoid 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;}}}
这篇关于Unity 3d让物体成弧线运动(可以制作炮弹发射的轨迹)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!