首页 > 解决方案 > unity2d如何让一个对象跟随另一个对象

问题描述

我一直在为此苦苦挣扎,我一直试图让我的敌人在玩家处于一定范围内时跟随玩家。我尝试使用 2dcollider 设置触发,但没有给出任何结果。

这是我的检测脚本,它位于具有触发 2d 盒对撞机的游戏对象上。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DetectPlayerScript : MonoBehaviour 
{
    public Rigidbody2D newtargetrb;
    public Transform newtarget;
    public bool FoundTarget;
    public Collider2D thiscollider;
    // Use this for initialization
    private void OnTriggerEnter2D(Collider2D other)
    {
        if(other.gameObject.tag == "Player")
        {
            newtarget = other.GetComponent<Transform>();
            newtargetrb = other.GetComponent<Rigidbody2D>();
            FoundTarget = true;
        }
    }
}

这是我用于在使用子对象和上面的脚本检测玩家之后应该跟随玩家的敌人的脚本。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ZombieStudent : MonoBehaviour 
{    
    public Transform  target;
    public Rigidbody2D Rb;
    public Rigidbody2D targetrb;
    // Use this for initialization
    void Start () 
    {
        var myhealth = GetComponent<BaseEnemyScript>().Health;
        var mydamage = GetComponent<BaseEnemyScript>().Damage;
        var mytarget = GetComponentInChildren<DetectPlayerScript>().newtarget;
        var TargetFound = GetComponentInChildren<DetectPlayerScript>().FoundTarget;
    }

    // Update is called once per frame
    void Update () 
    {
        target = GetComponentInChildren<DetectPlayerScript>().newtarget;
        var myspeed = GetComponent<BaseEnemyScript>().Speed;
        targetrb = GetComponentInChildren<DetectPlayerScript>().newtargetrb;
        if (GetComponentInChildren<DetectPlayerScript>().FoundTarget == true)
        {
            Vector2 TargetDIR = target.transform.position;
            Rb.AddForce(TargetDIR * myspeed);
        }
    }
}

我不确定 Rigidbody 2d 是否是造成这种情况的原因,但如果有帮助,这里是场景的屏幕截图。

图片

标签: c#unity3d2d

解决方案


发现答案只是将标签 Player 放在我的 Player Game Object 上。


推荐阅读