Weapon system system

is there a way so that the weapon is self-contained, what i mean is is can set specific qualities to each weapon, so when you pick it up it will do what i want it to specifically do, that way all the guns aren’t the same

1 Like

A simple yet efficient way to achieve different functionality per weapon is to first create an identifier so you can depict the weapons apart from one another (Weapon Name, Guid, Number, etc).

Next, create an array for your weapons and an object per weapon that stores a name, damage, or any other valid value to each weapon as it’s property. We may now loop over all weapons stored in the weapons array.

Then we embed a switch statement that uses the Weapon Identifier to depict what functionality is given to which weapon while ensuring we’re referencing the current weapon (entity the script is attached to).

Example Snippet (JSFiddle):

var weapons = [];
var activeWeapon = ''; // To keep track of weapon currently equipped (Held by player)

// Object defining the weapon's specs
var targetWeapon = {};
targetWeapon.name = 'Pistol'; // this.entity.name;
targetWeapon.damage = 25;
weapons.push(targetWeapon);

// Object defining another weapon's specs
var otherWeapon = {};
otherWeapon.name = 'Rifle';
otherWeapon.damage = 50;
weapons.push(otherWeapon);

// Specify which weapon is currently held by player (Pistol)
activeWeapon = targetWeapon.name; // this.entity.name; (Name of parent entity the script is in)

console.log('Weapons:', weapons);

// Loop over all weapons stored in array
for (var i = 0; i < weapons.length; i++) {
    var weapID = weapons[i].name; // Weapon Identifier

    // Iterate over all elements in weapons array by name
    switch (weapID) {
    	// Depict the target weapon specs from given name of weapon listed in array
        case 'Pistol':
            // If the parent entity of this script is the active weapon, assign the specs
            if (weapons[i].name == activeWeapon) {
                weaponName = weapons[i].name;
            	weaponDamage = weapons[i].damage;
            	console.log('Pistol equipped');
            }
            break;
        case 'Rifle':
            if (weapons[i].name == activeWeapon) {
            	weaponName = weapons[i].name;
            	weaponDamage = weapons[i].damage;
            	console.log('Rifle equipped');
            }
            break;
        default:
            weaponName = 'Hands';
            weaponDamage = 5;
            console.log('No weapon equipped');
            break;
    }
}

For this snippet to work, ensure the name of the entity (weapon) which this script will be attached to is listed in the switch clause or it will not work as intended.

With some tinkering you can add this code to one universal script and have it attached to all weapons. You can also specify your weapons’ objects in one single JSON-like object for better unification.

3 Likes