碰撞阻止敌人攻击-Unity3D
本文关键字:攻击 -Unity3D 敌人 碰撞 | 更新日期: 2023-09-27 18:26:50
我有一个简单的游戏,玩家保护中心基地不攻击敌人。目前,当玩家触碰基地时,所有敌人都停止攻击。攻击由Enemy脚本中的协同例程处理。我已经在下面发布了敌人和基地的脚本。敌方脚本
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);
}
}
基本脚本
using UnityEngine;
using System.Collections;
public class Base : MonoBehaviour {
public float Health = 100f;
public float AttackSpeed = 2f;
//VOID AWAKE - START . contains getcomponent code
public Enemy enemy;
void awake(){
enemy = GetComponent<Enemy>();
}
//VOID AWAKE - END
//If enemy touches the base
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;
}
}
//Coroutine that deals damage
public IEnumerator enemyAttack(){
while(Health > 0f){
if(enemy.isAttacking == true){
yield return new WaitForSeconds(2f);
Health -= Enemy.Damage;
Debug.Log ("Base health at: " + Health);
}else{
yield break;
}
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//Load Lose Screen when Base health reaches 0
if (Health <= 0){
Application.LoadLevel("Lose Screen");
}
}
}
我怀疑您的问题在于这里的逻辑:
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;
}
}
NoW你的情况是:
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;
}
}
现在,不是敌人接触你基地的东西不会停止影响敌人。
但是,当你在一个几乎没有或根本没有解释的问题中转储代码时,很难判断,所以这可能会有很大的差距