Rog*_*ger 3 quaternions unity-game-engine
我试图在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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
错误在于Quaternion.LookRotation的使用.
该函数采用两个Vector3作为输入,它们是世界空间中的前向(以及可选的向上矢量 - 默认Vector3.up),并返回Quaternion表示这种参考帧的方向的a.
相反,你提供一个世界空间位置作为输入(targetPosition),这是没有意义的.意外地,在世界空间中表示的归一化位置向量是从原点到给定点的方向,因此当塔放置在原点上时它可以正常工作.
您需要用作LookRotation参数的是从塔到目标的世界空间方向:
Vector3 aimDir = (targetPosition - transform.position).normalized;
desiredRotation = Quaternion.LookRotation (aimDir );
Run Code Online (Sandbox Code Playgroud)