我有一个炮塔放置为游戏对象,我已将目标设置为检查员中的敌人,但不知何故,炮塔只指向我的敌人,但不是在z轴上连续旋转。问题是什么,任何帮助都比x ... !!
这是我的代码
using UnityEngine;
using System.Collections;
public class TurretScript: MonoBehaviour
{
public Transform target;
void Update()
{
Vector3 tarPos = new Vector3(target.position.x, target.position.y, 10);
Vector3 lookPos = Camera.main.ScreenToWorldPoint(tarPos);
lookPos = lookPos - transform.position;
float angle = Mathf.Atan2(lookPos.y, lookPos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
答案 0 :(得分:0)
实现这一目标的最简单方法?作弊!像这样:
public class TurretScript: MonoBehaviour
{
//values that will be set in the Inspector
public Transform Target;
public float RotationSpeed;
void Update()
{
var direction = Target.transform.position - transform.position;
// Set Y the same to make the rotations turret-like:
direction.y = transform.position.y;
var rot = Quaternion.LookRotation(direction, Vector3.up);
transform.rotation = Quaternion.RotateTowards(
transform.rotation,
rot,
RotationSpeed * Time.deltaTime);
}
}
答案 1 :(得分:0)
您还可以使用Documentation
中的Transform.LookAt()我发现这是最简单的方法,没有计算轮换的麻烦。