Unity3d 四元数旋转
我正在尝试跟随一些unity3d Exmaple为塔防风格的游戏编写c#脚本。我需要一个炮塔来“瞄准”另一个游戏对象。我发现的例子似乎不能解释不是0,0,0的原点。也就是说,当炮塔位于不同的位置时,它的瞄准基于一个起点,而不是其当前位置 它现在的表现: 在我正在使用的脚本中,如何提供有关炮塔当前位置的Quaternion.LookRotation信息,以便将其包含在计算中?脚本,函数,第59行:Unity3d 四元数旋转,unity3d,quaternions,Unity3d,Quaternions,我正在尝试跟随一些unity3d Exmaple为塔防风格的游戏编写c#脚本。我需要一个炮塔来“瞄准”另一个游戏对象。我发现的例子似乎不能解释不是0,0,0的原点。也就是说,当炮塔位于不同的位置时,它的瞄准基于一个起点,而不是其当前位置 它现在的表现: 在我正在使用的脚本中,如何提供有关炮塔当前位置的Quaternion.LookRotation信息,以便将其包含在计算中?脚本,函数,第59行: using UnityEngine; using System.Collections; pub
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);
}
}
}
错误在于使用 该函数将两个
Vector3
作为输入,它们是世界空间中的前进方向(以及可选的上方向向量-默认Vector3.up
),并返回表示此类参考帧方向的四元数
而是提供一个世界空间位置作为输入(targetPosition
),这毫无意义。意外地,在世界空间中表示的规范化位置向量是从原点到给定点的方向,因此,当塔放置在原点上时,它可以正常工作
需要用作LookRotation参数的是从塔到目标的世界空间方向:
Vector3 aimDir = (targetPosition - transform.position).normalized;
desiredRotation = Quaternion.LookRotation (aimDir );
非常感谢。这是一个非常明确的回应。说到对细节的关注,您甚至在编辑我的代码时编辑了对行号的引用。谢谢