我花了两天时间检查这个脚本,但仍然没有发现我做错了什么。我想制作一个简单的AI飞机,从一个点飞到另一个点。到达第一个航点后,它应该飞向第二个航点。我将在下面附上我的脚本:
using UnityEngine; using System.Collections public class AICustomScript : MonoBehaviour { //第一个航点 public Transform Waypoint; //第二个航点 public Transform Waypoint2; void Start() { rb = GetComponent<Rigidbody>(); //使飞机朝向第一个航点的方向 transform.LookAt(Waypoint); } //允许我在编辑器中选择施加的力大小 public float AddForceAmount; //允许我在编辑器中选择飞机 public Rigidbody rb;/void FixedUpdate() {//使飞机移动 rb.AddForce(transform.forward * AddForceAmount); } //用于检测到达航点的代码部分 void OnTriggerEnter(Collider other){ if (other.gameObject) {//销毁航点 Destroy(other.gameObject); //使飞机朝向第二个航点(Waypoint2) transform.LookAt(Waypoint2); } } } //那么问题出在哪里?
我在注释中包含了我的逻辑思考。然而,当飞机到达第一个航点时,它会转向第二个航点,但只是部分转向。因此,虽然它正在飞向第二个航点,但永远不会“击中”它。为什么?
回答:
你可能需要使用球面插值来使飞机在改变位置时面向航点,而不是添加向前推力。
using UnityEngine;using System.Collections;public class AICustomScript : MonoBehaviour{ public Transform[] Waypoints; public float minimumTouchDistance = 2.0f; // 飞机与航点之间的最小距离 public float airplaneSpeed = 10.0f; private Transform currentWaypoint; // 跟踪当前航点 private int currentIndex; // 航点数组中的当前位置 void Start() { currentWaypoint = Waypoints[0]; // 设置初始航点 currentIndex = 0; // 设置初始索引 } void Update() { faceAndMove(); if (Vector3.Distance(currentWaypoint.transform.position, transform.position) < minimumTouchDistance) { currentIndex++; if (currentIndex > Waypoints.Length - 1) { currentIndex = 0; } currentWaypoint = Waypoints[currentIndex]; } } void faceAndMove() { Vector3 deltaPosition = currentWaypoint.transform.position - transform.position; Vector3 calcVector = deltaPosition.normalized * airplaneSpeed * Time.deltaTime; this.transform.position += calcVector; this.transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(deltaPosition), 4 * Time.deltaTime); } }