让敌人跟随Unity3D中的玩家

时间:2020-03-23 17:21:40

标签: c# unity3d

在玩家与地面碰撞后,我制作了一个脚本让敌人跟随玩家。

我面临的一个问题是敌人走到了起点而不是玩家。

如果有人可以帮助我,那将很酷:)

Transform tr_Player;
float f_RotSpeed = 3.0f, f_MoveSpeed = 3.0f;

public int gegnerLeben;
Rigidbody m_Rigidbody2;
Vector3 m_YAxis2;

public int leben;
public GameObject Player;
public GameObject verfolgen;
public GameObject MinenGener;

void Start()
{

    tr_Player = Player.transform;

    m_Rigidbody2 = GetComponent<Rigidbody>();
    m_YAxis2 = new Vector3(0, 5, 0);

}


public void GegnerFreez()
{
    m_Rigidbody2.constraints = RigidbodyConstraints.FreezePosition;
}

void Update()
{
    if (Player.GetComponent<SpielerScript>().MineBetreten == true)
    {
        MinenGener.transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(tr_Player.position - transform.position), f_RotSpeed * Time.deltaTime);
        MinenGener.transform.position += transform.forward * f_MoveSpeed * Time.deltaTime;
    }


    if (gegnerLeben < 1)
    {
        Destroy(Player.GetComponent<SpielerScript>().MinenGegner);
    }
}

1 个答案:

答案 0 :(得分:1)

这里有几点:

请勿一遍又一遍地使用GetComponent中的Update

宁可让您输入字段类型

public SpielerScript Player;

,然后通过检查器将播放器拖入。这有两件事

  • 检查对象是否甚至附加了SpielerScript并仅允许放置然后
  • 已经存储了对SpielerScript的引用,因此无需使用GetComponent

m_Rigidbody2也可以通过检查器进行引用

[SerializeField] Rigidbody m_Rigidbody2;

然后Quaternion.Slerp01之间给定因子旋转之间的线性插值。在这里使用乘以Time.deltaTime的因数是没有意义的,因为您得到的将类似于3 * 0.017(60 f / s),导致插值因数约为0.051,因此非常接近0,因此您的敌人只会非常缓慢地改变其旋转速度!

而是使用固定值,例如0.5为了使每一帧都设置在两次旋转之间的中间位置,或者0.25为了使其变慢。

经过一些清理和重构后,您的代码可能看起来像

[Header("References")]
[SerializeField] private PlayerScript Player;
[SerializeField] private Rigidbody m_Rigidbody2;
[SerializeField] private Transform MinenGener;

public GameObject verfolgen;

[Header("Settings")]
[SerializeField] [Range(0,1)] private float f_RotFactor = 0.5f
[SerializeField] private float f_MoveSpeed = 3.0f;

[Header("Runtime Values")]
public int leben;
public int gegnerLeben;

private Transform tr_Player;
private Vector3 m_YAxis2 = new Vector3(0, 5, 0);

private void Start()
{
    tr_Player = Player.transform;

    // only do as fallback if not referenced via the Inspector to save resources
    if(!m_Rigidbody2) m_Rigidbody2 = GetComponent<Rigidbody>();
}

public void GegnerFreez()
{
    m_Rigidbody2.constraints = RigidbodyConstraints.FreezePosition;
}

void Update()
{
    if (Player.MineBetreten)
    {
        MinenGener.transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(tr_Player.position - transform.position), f_RotFactor);
        MinenGener.transform.position += transform.forward * f_MoveSpeed * Time.deltaTime;
    }

    if (gegnerLeben < 1)
    {
        Destroy(Player.MinenGegner);
    }
}