top of page

GRENADES!

This week I have added an exciting feature… GRENADES!

When the player presses the key Q, they will be able to throw a grenade which will explode after 3 seconds. I have 2 scripts, one attached to the player and one on the grenade.


This one is on the grenade:

So there is a countdown that occurs ibn the update, so when the grenade is thrown, it waits 3 seconds and then if the countdown has reached 0 and grenade has not exploded (!hasExploded) then the Explode function is called and there is an explosion effect instantiated and has exploded is set to true.


public class Grenade : MonoBehaviour
{
 public float grenadeDelay = 3f;
 float countdown;
 bool hasExploded = false;
 public GameObject explosionEffect;
 void Start()
 {
 countdown = grenadeDelay;
 }

 void Update()
 {
 countdown -= Time.deltaTime;
 if(countdown <= 0f && !hasExploded)
 {
 Explode();
 hasExploded = true;
 }
 }

 void Explode()
 {
 Debug.Log("Boom");
 Instantiate(explosionEffect, transform.position, transform.rotation);
 Destroy(gameObject);
 }
}

This is the other script that is on the player:

This script controls the throwing of the grenade, so in the update function, If the player has pressed the ‘Q’ key, the ThrowingGrenade function is called and the prefab appears in the scene, I have put this just behind the camera so it seems as if it’s being thrown, it gets the rigid body and then so that the grenade is always going to be thrown where the camera is facing and multiply it by add force. We do not care for the mass of the object and this is not a force we apply over time, the code, ForceMode.VelocityChange is used


public class ThrowGrenade : MonoBehaviour
{
 public float throwForce = 30f;
 public GameObject grenadePrefab;
 public GameObject Playerseyes;

 void Update()
 {
 if (Input.GetKeyDown("q"))
 {
 ThrowingGrenade();
 }
 }
 void ThrowingGrenade()
 {
 GameObject grenade = Instantiate(grenadePrefab, 
 Playerseyes.gameObject.transform.position, 
 Playerseyes.gameObject.transform.rotation);
 Rigidbody rb = grenade.GetComponent<Rigidbody>();
 rb.AddForce(transform.forward * throwForce, ForceMode.VelocityChange);

 }

 }


Here is a little clip of it:


Yorumlar


  • YouTube
  • Instagram
  • LinkedIn

Google Play and the Google Play logo are trademarks of Google LLC.

bottom of page