C# 碰撞阻止敌人攻击-Unity3D
我有一个简单的游戏,玩家防守一个中心基地,不让敌人进攻。目前当玩家触及基地时,敌人都停止攻击。攻击由敌人脚本中的一个联合例程处理。我已经在下面发布了敌人和基地脚本。 敌书C# 碰撞阻止敌人攻击-Unity3D,c#,unity3d,boolean,collision,C#,Unity3d,Boolean,Collision,我有一个简单的游戏,玩家防守一个中心基地,不让敌人进攻。目前当玩家触及基地时,敌人都停止攻击。攻击由敌人脚本中的一个联合例程处理。我已经在下面发布了敌人和基地脚本。 敌书 using UnityEngine; using System.Collections; public class Enemy : MonoBehaviour { public static float Damage = 10.0f; public float Health = 20.0f; public Transfo
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour {
public static float Damage = 10.0f;
public float Health = 20.0f;
public Transform target;
public float Speed;
public bool isAttacking = false;
//If the player collides with the enemy
void OnTriggerEnter2D(Collider2D col)
{
if(col.gameObject.tag == "Player")
{
Debug.Log("Player hits enemy");
Health -= PlayerController.Damage;
Debug.Log("Enemy health at: " + Health);
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//Destroy the enemy if it's health reaches 0
if(Health <= 0){
isAttacking = false;
Debug.Log ("Is attacking: " + isAttacking);
Destroy(this.gameObject);
Debug.Log ("Enemy Destroyed!");
}
//Constantly move the enemy towards the centre of the gamespace (where the base is)
float step = Speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
}
}
使用UnityEngine;
使用系统集合;
公共阶级敌人:单一行为{
公共静态浮子损坏=10.0f;
公共卫生=20.0f;
公共转型目标;
公众浮标速度;
公共bool isAttacking=false;
//如果玩家与敌人相撞
无效OnTriggerEnter2D(碰撞的R2D列)
{
如果(col.gameObject.tag==“玩家”)
{
Log(“玩家击中敌人”);
健康-=游戏控制器。损坏;
Debug.Log(“敌人生命值:”+生命值);
}
}
//用于初始化
无效开始(){
}
//每帧调用一次更新
无效更新(){
//如果敌人的生命值达到0,则摧毁敌人
如果(运行状况0f){
敌方.isAttacking=true;
调试日志(“敌人攻击基地”);
开始例行程序(“敌人攻击”);
}
否则{
敌方攻击=错误;
}
}
//造成伤害的协同程序
公共IEnumerator enemyAttack(){
而(运行状况>0f){
if(敌方攻击==真){
产生返回新的WaitForSeconds(2f);
生命-=敌人。伤害;
Log(“基本运行状况在:“+运行状况”);
}否则{
屈服断裂;
}
}
}
//用于初始化
无效开始(){
}
//每帧调用一次更新
无效更新(){
//基本运行状况达到0时加载丢失屏幕
如果(健康我怀疑你的问题在于这里的逻辑:
void OnCollisionEnter2D(Collision2D col){
Debug.Log ("Base touched");
if(col.gameObject.tag == "Enemy" && Health > 0f){
enemy.isAttacking = true;
Debug.Log ("Enemy attacking base");
StartCoroutine("enemyAttack");
}
else{
enemy.isAttacking = false;
}
}
现在你的情况是:
if(col.gameObject.tag == "Enemy" && Health > 0f)
因此,如果与基地相撞的东西(如果我理解正确)不是“敌人”,那么你进入else子句:
enemy.isAttacking = false;
阻止敌人进攻
可能您想要的是:
if (col.gameObject.tag == "Enemy")
{
if (Health > 0f)
{
//...do stuff
}
else
{
enemy.isAttacking = false;
}
}
现在不是敌人的东西接触你的基地不会停止影响敌人
但是当你在一个几乎没有解释或没有解释的问题中转储代码时,很难判断,所以这可能是远远不够的。那么你的问题是什么。。我还要问一下,你是否在你发布的当前代码中设置了断点并进行了逐步处理。。这有点难说,但基本上,当玩家触底时,它会阻止敌人攻击正在确认。我不希望发生这种情况。我现在正在添加断点,并以稍微慢一点的速度遍历代码,但如果是明显的问题,我只希望得到一些指针。Nobody有时间遍历大量的代码转储。您需要先使用正常的调试过程来缩小问题的范围。先这样做,然后在仍然需要的情况下发布大多数人不会回答关于游戏的问题,因为不是所有的程序员都做游戏开发,所以可能需要为这种类型的游戏开一个单独的房间stuff@MethodMan我想他们做到了:
if (col.gameObject.tag == "Enemy")
{
if (Health > 0f)
{
//...do stuff
}
else
{
enemy.isAttacking = false;
}
}