我一直在为此奋斗,我一直试图让我的敌人在玩家处于某个范围内时跟随玩家。我尝试使用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是否是造成这种情况的原因,但如果这有帮助,这里是一个场景的屏幕截图。
答案 0 :(得分:0)
发现答案只是将标记播放器放在我的播放器游戏对象上。