c# - 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 是否是造成这种情况的原因,但如果有帮助,这里是场景的屏幕截图。
解决方案
发现答案只是将标签 Player 放在我的 Player Game Object 上。
推荐阅读
- arrays - 在常见的 lisp 中,使用 '#(...) 或仅使用 #(...) 创建向量有什么区别?
- python - SQL 中的中间聚合函数和数据操作
- azure - 有没有办法使用二头肌将 Azure 防火墙连接到 Front Door 高级策略?
- swift - xcode12 如何将.md 文件的字体更改为等宽字体?
- javascript - 展平嵌套的 JSON 对象
- python - 一次将多个 tkinter 菜单项设置为“正常”的最有效方法是什么?
- python - 你如何在 Numpy 中创建一个(有时)参差不齐的数组?
- xcode - 为什么 datePicker View 的转换不能按预期工作?
- css - 根据特定事件的进度为自定义贝塞尔曲线设置动画
- rust - Rust Calamine 可选解析器在第一个空单元格处停止读取行