首页 > 解决方案 > 如何让我的 NPC 指向一个航点?

问题描述

从任何意义上来说,我都是一个新手,不知道该怎么做。我知道这是带有向量的东西。这是我当前的代码。问题是 npc 转向并面向航路点所面对的方向,而不是指向它的相对方向。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Waypoints : MonoBehaviour
{

    public GameObject[] waypoints;
    public GameObject player;
    int current = 0;
    public float speed;
    public float rotSpeed;
    float WPradius = 1;

    void Update()
    {
        if (Vector3.Distance(waypoints[current].transform.position, transform.position) < WPradius)
        {
            current = Random.Range(0, waypoints.Length);
            if (current >= waypoints.Length)
            {
                current = 0;
            }
        }
        
        transform.position = Vector3.MoveTowards(transform.position, waypoints[current].transform.position, Time.deltaTime * speed);
        transform.rotation = Quaternion.RotateTowards(transform.rotation, waypoints[current].transform.rotation, Time.deltaTime * rotSpeed);
        
    }

   
} ```

标签: c#unity3d

解决方案


使用waypoints[current].transform.rotationinRotateTowards将获得对象的旋转。您对旋转感兴趣,它使局部前向点在 from transform.positionto的方向上,waypoints[current].transform.position并且还使局部向上尽可能接近全局向上。您可以使用Quaternion.LookRotation来确定旋转:

void Update()
{
    if (Vector3.Distance(waypoints[current].transform.position, transform.position) 
            < WPradius)
    {
        current = Random.Range(0, waypoints.Length);
        if (current >= waypoints.Length)
        {
            current = 0;
        }
    }
    
    Vector3 waypointPos = waypoints[current].transform.position;
    transform.position = Vector3.MoveTowards(transform.position, waypointPos,
            Time.deltaTime * speed);

    Quaternion goalRot = Quaternion.LookRotation(waypointPos - transform.position);
    transform.rotation = Quaternion.RotateTowards(transform.rotation, goalRot, 
            Time.deltaTime * rotSpeed);
    
}


推荐阅读