【发布时间】:2018-05-04 19:52:41
【问题描述】:
我一直在为此苦苦挣扎,我一直试图让我的敌人在玩家处于一定范围内时跟随玩家。我尝试使用 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 是否是造成这种情况的原因,但如果有帮助,这里是场景的屏幕截图。
【问题讨论】:
-
你试过调试
OnTriggerEnter2D(Collider2D other)函数吗?首先调试并查看断点是否在函数内部被命中。然后发布更新的信息。您也可以使用Debug.Log()对其进行测试,以查看是否触发输入发生 -
感谢您的提示,这时我注意到我没有在我的玩家游戏对象上添加玩家标签。我是个笨蛋。
-
它发生了。我们都会犯错。很高兴它帮助了你 :) 你可以写下自己的答案并将其标记为已关闭。