Answer the question
In order to leave comments, you need to log in
How to make a grenade explosion with damage that will not go through walls (colliders)?
Hello, I'm trying to implement a grenade, but I ran into such a problem: during the explosion, the player takes damage even if he is behind the wall.
Here are my 2 grenade implementations:
using System.Collections.Generic;
using UnityEngine;
public class GranadeBulletScript : MonoBehaviour {
private float timeDetected = 5f;
private List<GameObject> playerInTrigger = new List<GameObject>();
// Use this for initialization
void Start () {
gameObject.GetComponent<Rigidbody>().velocity = gameObject.transform.forward * 20;
}
// Update is called once per frame
void Update () {
timeDetected -= Time.deltaTime;
if(timeDetected <= 0)
{
foreach (GameObject hit in playerInTrigger)
Damage(hit);
Destroy(gameObject);
}
}
private void Damage(GameObject hit)
{
var health = hit.GetComponent<Player>();
if (health != null)
{
health.TakeDamage(100f);
}
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
playerInTrigger.Add(other.gameObject);
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Player")
playerInTrigger.Remove(other.gameObject);
}
}
using UnityEngine;
public class GranadeScript : MonoBehaviour
{
[SerializeField] private float damage;
[SerializeField] private float radius;
[SerializeField] private float timeOfExplode;
private void Damage(GameObject hit)
{
var health = hit.GetComponent<Player>();
if (health != null)
{
health.TakeDamage(damage);
}
}
private void Update()
{
timeOfExplode -= Time.deltaTime;
if (timeOfExplode <= 0)
{
Collider[] colls = Physics.OverlapSphere(transform.position, radius);
foreach (Collider coll in colls)
{
if (coll.gameObject.tag == "Player")
{
Debug.Log("Boom");
Damage(coll.gameObject);
}
}
}
}
private void OnDrawGizmos()
{
Gizmos.DrawWireSphere(transform.position, radius);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question