Unity3d 在unity 3d中使用行星引力时,剑客之剑如何指向目标并跟随目标?

Unity3d 在unity 3d中使用行星引力时,剑客之剑如何指向目标并跟随目标?,unity3d,3d,Unity3d,3d,我想知道是否有人能帮我做这件事。我正试图让一名敌方剑客跟随我的玩家,并将剑对准我,但我似乎不明白为什么它不起作用,而且没有武器指向代码,它也会起作用 private void FixedUpdate() { Follow(target); rb.MovePosition(rb.position + transform.TransformDirection(moveDir) * walkSpeed * Time.deltaTime);

我想知道是否有人能帮我做这件事。我正试图让一名敌方剑客跟随我的玩家,并将剑对准我,但我似乎不明白为什么它不起作用,而且没有武器指向代码,它也会起作用

    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);
    }
这里有一段视频

这是一个没有瞄准的视频

下面是一个视频,当使用lookat时,它会变得很奇怪,lookat是解决这个问题的完美方法

考虑到以下情况,剑有一个枢轴和一个能够独立移动的父级以及一个目标。见示例:

在pivot上附加一个非常简单的脚本,以确保pivot将查看目标。此外,确保剑沿+Z轴向前移动:

在pivot上的脚本中,编写以下内容:

//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所说,它不能保证恒定的运动。

speed=targetVector.magnity*5?这对我来说毫无意义,为什么敌人离你越远,移动得越快?@Draco18s这与你想要移动的目的有关,所以你必须不断行动。这段脚本是附在剑上还是附在敌人身上?@c0d3d好的,那么为什么targetVector.normalized?从这两行得到的结果与targetVector*5相同。