Throw a Grenade
The grenade throw mechanic is very different from the typical gunfire mechanic — enough that they should both use the firing script but act completely different. To do this, let’s first start by separating them by adding an enum to the firing script.
By adding this enum script, we can choose on the prefab if we will be using the grenade throwable or a gun. This is also good for caching variables at start.
If we have a grenade type, then what we want to do is run a throwable script from a throwable object. Create a throwposition gameobject and place that object where you want the player to throw.
Inside our script, we will in start check — if we have a gun, cache the anim and particles. If we have a grenade, find the throw position.
We need to set a bool condition otherwise we will simply spawn a ton of grenades on throw. so when we throw, let’s invoke a throw grenade function that will get the throw object script on the throw position and run a throw object function.
When we throw, the canThrow is true, once thrown, it’s false.
Next, let’s look at our throw object script. We want this to be a separate script from fire weapon because fire weapon doesn’t need to know how to fire, it just needs to know when. In the throw object script, we will tell our object how to throw our grenade. First, we need a throwable which is our grenade and instantiate that.
After we instantiate it, we want to then add a rigid body and enable our collider on the gameobject.
Finally, whenever we throw, we will throw from the current objects rotation, but our throw position gameobject doesn’t actually rotate. Our root player capsule does. Because of this, the direction we throw will always be the same. We need to grab the current rotation of our character, adjust the instantiation of our grenade to match that, and then apply force.
Finally, we need to apply force to our grenade. This means we need to apply the direction but since it’s a grenade, we need to apply a torque as well.
Once that’s complete, our grenade throwing mechanic should be complete.