c# - 如何让我的 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);
}
} ```
解决方案
使用waypoints[current].transform.rotation
inRotateTowards
将获得对象的旋转。您对旋转感兴趣,它使局部前向点在 from transform.position
to的方向上,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);
}
推荐阅读
- excel - PowerBI:从混合文件夹文件中导入数据
- kotlin - 如何调用入队回调?
- ios - 保存的 VPN 配置需要更新吗?
- tensorflow - ValueError:无法将 NumPy 数组转换为张量(不支持的对象类型 numpy.ndarray)
- css - top/bottom 和 left/right: auto 如何与绝对定位一起工作?
- leaflet - 如何从本地 geojson 文件在传单地图上添加点?
- python - 从 pyspark 数据框字符串列中获取第一个数值到新列中
- azure - Azure AD 保护来自 Angular 前端的 .Net Core Web API 3.1 返回 401 和 MSAL
- php - 如何在PHP中使用动态键遍历数组
- mysql - Time column value change without touching it