【发布时间】:2021-11-06 16:50:21
【问题描述】:
问题: 当敌人活着时,它的子弹脚本爆炸效果会反复发生在其身体对象上。当我杀死敌人时,子弹开始按原样射出。为什么子弹只有在敌人死亡时才起作用? screenshot from bullet exploding on gameobject
项目符号脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletScriptEnemy : MonoBehaviour
{
GameObject target;
public float speed;
Rigidbody2D bulletRB;
//
public GameObject hitEffect;
public int damage = 40;
public Rigidbody2D rb;
//
// Start is called before the first frame update
void Start()
{
bulletRB = GetComponent<Rigidbody2D>();
target = GameObject.FindGameObjectWithTag("Player");
Vector2 moveDir = (target.transform.position - transform.position).normalized * speed;
bulletRB.velocity = new Vector2(moveDir.x, moveDir.y);
Destroy(this.gameObject, 2);
}
void OnTriggerEnter2D(Collider2D hitInfo)
{
GameObject effect = Instantiate(hitEffect, transform.position, Quaternion.identity);
Destroy(effect, 2f); //Sekundes
Destroy(gameObject);
Player player = hitInfo.GetComponent<Player>();
if(player != null)
{
player.TakeDamage(damage);
}
Destroy(gameObject);
}
// Update is called once per frame
void Update()
{
}
}
敌人的脚本:
public class Enemy : MonoBehaviour
{
public Animator animator;
public int maxHealth = 100;
//public GameObject deathEffect;
int currentHealth;
// Start is called before the first frame update
void Start()
{
currentHealth = maxHealth;
}
public void TakeDamage(int damage)
{
currentHealth -= damage;
//Play hurt animation
animator.SetTrigger("Hurt");
if(currentHealth <= 0)
{
Die();
}
}
void Die()
{
Debug.Log("Enemy died!");
//Instantiate(deathEffect, transform.position, Quaternion.identity);
//Destroy(gameObject);
//Die anim
animator.SetBool("IsDead", true);
//Disable the enemy
GetComponent<Collider2D>().enabled = false;
this.enabled = false;
}
}
【问题讨论】:
-
子弹在与玩家发生碰撞之前必须与敌人发生碰撞。更改子弹生成位置