Part 4: Weaponry Scripts

Now that I have all of the 3D Models for the weapons, it was time to actually create scripts so that the player can launch projectiles, instantiating at the players head, then shooting out in the players looking direction, at a certain velocity to imitate a bullet. Each weapon needs to have different speed and shot delay, and I need to create a script that only allows one gun to be equipped at one time until the player chooses to drop that specific gun. That means I need a weapon manager script, as well as a script for each gun and each different bullet type.

The way that I checked if the player is looking at a gun, which gun it is, and if they have a gun already equipped, is by casting a raycast directly from the players face, pointing out in the forward vector of the camera.

This weaponry grab is attached to the player, so that it works only when the player is active.

To check if a gun is equipped, each gun has a number ID, with bare hands being 0. This way, whenever a gun is equipped, this number changes to either 1,2 or 3. Then switches back to 0 whenever the gun drop function is called. So in the if function statement, it also checks if the WeaponEquipped ID is at 0.

Each weapon has its own raycast

When the E button has been pressed, it destroys the world object of the weapon that the player is looking at, then calls the equivalent function for grabbing that specific weapon.

The GrabPistol function

When the player grabs a weapon, it switched the currentWeapon ID to that weapons id, and spawns the usable gun into the players hand using the instantiate function. It then also becomes parented to the fps camera, so it rotates with the view.

The Drop Function

When the player drops a weapon, the gun is destroyed in the players hands, then the weapon ID is reset to be bare hands. The gun in floor mode is spawned then given a force push as if the player is thrown. This entire script then loops and repeats whenever guns are grabbed, dropped or used.

This script is how the pistol shoots and sends out projectiles bullets. Each gun has similar code, but is changed slightly for the variation of weapon it comes from. When the mouse button is clicked, the gun fires a single projectile at a certain force velocity. A fire delay is then set inside of a co-routine, so that the player can’t spam fire fast and break the realism of the weaponry. The bullets then destroy themselves after 1 second, to add the idea of some sort of range, so that pistols can’t snipe people.

Leave a comment

Design a site like this with WordPress.com
Get started