首页 > 解决方案 > 在统一 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

标签: unity3d3d

解决方案


Lookat()是这个问题的完美解决方案。


鉴于以下情况,有一个枢轴和一个能够独立移动的父级和一个目标。参见示例:

例子

在枢轴上附加一个非常简单的脚本,以确保枢轴将注视目标。另外,确保剑在+Z 轴上前进:

正 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 所说,它不能确保持续运动。


推荐阅读