【问题标题】:Why the turret is not rotating when detecting the player in specific range?为什么在特定范围内检测到玩家时炮塔不旋转?
【发布时间】:2017-11-24 02:10:29
【问题描述】:

这是脚本,我也将它附加到聚光灯上,当玩家在路点之间移动时,聚光灯会旋转并照亮玩家。

但是,当我将脚本也附加到炮塔时,炮塔会旋转 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);
        }
    }
}

【问题讨论】:

  • 你的问题到底是什么?
  • @roelofs 为什么炮塔没有面向玩家旋转。玩家在航路点之间移动,但炮塔没有跟踪它。但是,如果附加脚本例如用于聚光灯,则当玩家在范围内时,聚光灯将继续跟踪玩家。
  • 那么炮塔代码是什么样子的呢?我认为这信息太少,无法处理。
  • @roelofs 在我的问题中,我添加了脚本,这是附加到炮塔的脚本。对于一个测试,我用球体和立方体创建了一个我自己的炮塔,它旋转得很好。我只是想知道这个炮塔有什么问题。

标签: c# unity3d unity5


【解决方案1】:

使用 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);


你可以看一下“完成”代码

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    相关资源
    最近更新 更多