一:實現效果
二:第一種實現方法——弧形插值
using UnityEngine;
public class ArcMove : MonoBehaviour
{
public GameObject curGo;//當前物體
public GameObject targetGo;//目標物體
public float value;
private void Update()
{
//計算中心點
Vector3 center = (curGo.transform.position + targetGo.transform.position) / 2;
center -= new Vector3(0, value, 0);
Vector3 start = curGo.transform.position - center;
Vector3 end = targetGo.transform.position - center;
//弧形插值
curGo.transform.position = Vector3.Slerp(start, end, Time.time / 200);
curGo.transform.position += center;
//斷定是否到達目標點
float dis = Vector3.Distance(curGo.transform.position, targetGo.transform.position);
if (dis <= 1)
{
Debug.Log("到達目標點");
}
}
}
三:第二種實現方法——計算弧線中的夾角
using UnityEngine;
using System.Collections;
public class ArcMove : MonoBehaviour
{
public GameObject curGo;//當前物體
public GameObject targetGo;//目標物體
public float speed = 2;//速度
public int rotationAngle = 60;//旋轉的角度
private float distanceToTarget;//二者之間的距離
private bool move = true;//是否移動
void Start()
{
//計算二者之間的距離
distanceToTarget = Vector3.Distance(curGo.transform.position, targetGo.transform.position);
StartCoroutine(Move());
}
/// <summary>
/// 移動
/// </summary>
private IEnumerator Move()
{
//移動到目標點中止移動
while (move)
{
Vector3 targetPos = targetGo.transform.position;
targetPos.z = 0;
//讓它始終朝着目標
curGo.transform.LookAt(targetPos);
//計算弧線中的夾角
float angle = Mathf.Min(1, Vector3.Distance(curGo.transform.position, targetPos) / distanceToTarget) * rotationAngle;
curGo.transform.rotation = curGo.transform.rotation * Quaternion.Euler(Mathf.Clamp(-angle, -42, 42), 0, 0);
float currentDist = Vector3.Distance(curGo.transform.position, targetGo.transform.position);
if (currentDist < 0.5f)
{
move = false;
Debug.Log("到達目標點");
}
curGo.transform.Translate(Vector3.forward * Mathf.Min(speed * Time.deltaTime, currentDist));
yield return null;
}
}
}