这是脚本我还将它附加到聚光灯上,当玩家在航点之间移动时,聚光灯会旋转并点亮玩家。
但是当我将剧本附加到炮塔时,我的炮塔旋转180度然后停止并且永远不会继续旋转跟踪玩家。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotateSpotlight : MonoBehaviour
{
public GameObject target;
public float smooth = 1f;
public float rangeSqr;
public float rotationSpeed;
Quaternion originalRotation;
private void Start()
{
originalRotation = transform.localRotation;
}
private void Update()
{
if (target.transform.position.x < transform.position.x + rangeSqr)
{
var targetRotation = Quaternion.LookRotation(target.transform.position - transform.position);
var str = Mathf.Min(rotationSpeed * Time.deltaTime, 1);
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, str);
}
else
{
var str = Mathf.Min(rotationSpeed * Time.deltaTime, 1);
transform.rotation = Quaternion.Lerp(transform.rotation, originalRotation, str);
}
}
}
答案 0 :(得分:0)
使用VectorX.Distance()比使用pos x和pos y更好,更敏感。
我很确定你的问题来自于Quaternion.LookRotation,这个功能并没有给你你所期望的价值。
我个人用它进行角度计算:
Vector3 a = targetPos - _transform.position;
Vector3 b = Vector3.forward;
float angle = Vector3.Angle(a, b);
float finalAngle = (Vector3.Cross(a, b).y > 0 ? -angle : angle);
您可以查看“complet”代码
private void Update()
{
//check range
if (Vector3.Distance(targetPos, turretPos) < maxRange)
AutoAttack(targetPos);
}
public override void AutoAttack(Vector3 targetPos)
{
Vector3 a = targetPos - _transform.position;
Vector3 b = Vector3.forward;
float angle = Vector3.Angle(a, b);
Rotation(Vector3.Cross(a, b).y > 0 ? -angle : angle);
//this condition is to to fire only when the turret is currently looking at target
if (Mathf.Abs(Mathf.DeltaAngle(_transform.eulerAngles.y, (Vector3.Cross(a, b).y > 0 ? -angle : angle))) < minAngleToFire)
Attacking();
}
//call to rotate the in y axis
public void RotationY(float angle)
{
_transform.rotation = Quaternion.Lerp(_transform.rotation, Quaternion.Euler(0, angle, 0), Time.deltaTime * rotationSpeed);
}