四元数LookRotation

时间:2015-01-01 17:56:32

标签: unity3d quaternions

我正试图在c#scripting上关注塔式防御风格游戏中的一些unity3d exmaples。我需要一个炮塔来瞄准'在另一个游戏对象。我找到的例子似乎没有说明不是0,0,0的原点。意思是,当炮塔位于不同的位置时,它的目标是起点,而不是它的当前位置。

它现在的表现如何: http://screencast.com/t/Vx35LJXRKNUm

在我使用的脚本中,如何提供有关炮塔当前位置的Quaternion.LookRotation信息,以便将其包含在其计算中?脚本,函数CalculateAimPosition,第59行:

using UnityEngine;
using System.Collections;

public class TurretBehavior : MonoBehaviour {

public GameObject projectile;
public GameObject muzzleEffect;

public float reloadTime = 1f;
public float turnSpeed = 5f;
public float firePauseTime = .25f;

public Transform target;
public Transform[] muzzlePositions;
public Transform turretBall;

private float nextFireTime;
private float nextMoveTime;
private Quaternion desiredRotation;
private Vector3 aimPoint;

// Update is called once per frame
void Update () 
{
    if (target) 
    {
        if (Time.time >= nextMoveTime) 
        {
            CalculateAimPosition(target.position);
            transform.rotation = Quaternion.Lerp(turretBall.rotation, desiredRotation, Time.deltaTime * turnSpeed);     
        }   

        if (Time.time >= nextFireTime) {
            FireProjectile();
        }
    }
}

void OnTriggerEnter(Collider other)
{
    if (other.gameObject.tag == "TurretEnemy") 
    {
        nextFireTime = Time.time +(reloadTime *.5f);
        target = other.gameObject.transform;
            }

}

void OnTriggerExit(Collider other)
{
    if (other.gameObject.transform == target) {
        target = null;
            }
}

void CalculateAimPosition(Vector3 targetPosition)
{
    aimPoint = new Vector3 (targetPosition.x, targetPosition.y, targetPosition.z);
    desiredRotation = Quaternion.LookRotation (aimPoint);
}

void FireProjectile()
{
    nextFireTime = Time.time + reloadTime;
    nextMoveTime = Time.time + firePauseTime;

    foreach(Transform transform in muzzlePositions)
    {
        Instantiate(projectile, transform.position, transform.rotation);
    }
}
}

1 个答案:

答案 0 :(得分:6)

错误在于使用Quaternion.LookRotation

该函数将两个Vector3作为输入,这是世界空间中的前向(以及可选的向上向量 - 默认Vector3.up),并返回表示此类方向的Quaternion参考框架。

您提供世界空间位置作为输入(targetPosition),这没有任何意义。意外地,在世界空间中表示的标准化位置向量是从原点到给定点的方向,因此当塔放置在原点时它可以正常工作。

您需要用作LookRotation参数的是从塔到目标的世界空间方向:

Vector3 aimDir = (targetPosition - transform.position).normalized;
desiredRotation = Quaternion.LookRotation (aimDir );