亲宝软件园·资讯

展开

Unity弧形移动 Unity实现弧形移动效果

LLLLL__ 人气:0

一、实现效果

二、第一种实现方法——弧形插值

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

加载全部内容

相关教程
猜你喜欢
用户评论