unity3d - 在统一 3d 中使用行星重力时,剑士剑如何指向目标并跟随它?
问题描述
我想知道是否有人可以帮助我解决这个问题。我试图让一个敌方剑客跟随我的玩家并将剑对准我,但我似乎无法理解为什么它不起作用并且 spazz 出来了(它在没有武器指向代码的情况下工作)
private void FixedUpdate()
{
Follow(target);
rb.MovePosition(rb.position + transform.TransformDirection(moveDir) * walkSpeed * Time.deltaTime);
AimTowards();
}
public void Follow(Transform target)
{
Vector3 targetVector = target.position - transform.position;
float speed = (targetVector.magnitude) * 5;
Vector3 directionVector = targetVector.normalized * speed;
directionVector = Quaternion.Inverse(transform.rotation) * directionVector;
moveDir = new Vector3(directionVector.x, directionVector.y, directionVector.z).normalized;
}
void AimTowards()
{
float angle = Mathf.Atan2(moveDir.y, moveDir.x) * Mathf.Rad2Deg;
pivot.localRotation = Quaternion.AngleAxis(angle - 90, Vector3.down);
}
这是它的视频https://vimeo.com/364530113
这是一个没有瞄准的视频https://vimeo.com/364530129
这是使用lookat时的视频(它变得很奇怪)https://vimeo.com/364530148
解决方案
Lookat()
是这个问题的完美解决方案。
鉴于以下情况,剑有一个枢轴和一个能够独立移动的父级和一个目标。参见示例:
在枢轴上附加一个非常简单的脚本,以确保枢轴将注视目标。另外,确保剑在+Z 轴上前进:
在枢轴上的脚本中写下以下内容:
//Target object
public Transform target;
//Pivot object (in this case the object the script is attached to)
public Transform pivot;
//Might want to use Update() instead
private void FixedUpdate()
{
//Simply look at the target
pivot.LookAt(target);
}
无论父对象是旋转还是平移,剑都应该指向起点。
此外,在您的脚本中:
Vector3 targetVector = target.position - transform.position;
float speed = (targetVector.magnitude) * 5;
Vector3 directionVector = targetVector.normalized * speed;
可以简化为:
Vector3 targetVector = target.position - transform.position;
float speed = 5.0f;
Vector3 directionVector = targetVector * speed;
因为归一化会将向量的大小更改为 1,因此,将其乘以真实大小将使其从未归一化。正如@Draco18s 所说,它不能确保持续运动。
推荐阅读
- machine-learning - 为什么我应该在应用机器学习算法之前减少数据的偏度?
- python - 如何计算在达到下一个值之前还剩多少行?
- c# - 如何在主窗体中等待在另一个线程中触发并完成的事件而不阻塞 UI
- local-variables - 如何在 EB GUIDE 脚本中定义局部变量
- sql-server - 获取每个员工的作用域角色
- git - 使用 web ui 擦除提交
- swift - 检测 iOS 暗模式更改
- tensorflow - TensorRT 如何处理数据?
- python - 使 Spark 结构化流中的 JSON 可以在 python (pyspark) 中作为没有 RDD 的数据帧访问
- angular - Webpack Live Reload 总是落后一步