Authoring your first weapon entity

From Valve Developer Community
Revision as of 20:40, 6 May 2017 by Atom (talk | contribs)

Jump to: navigation, search


It should not come as a surprise that the Source engine has a very robust weapon system. This article will cover creating a weapon entity from scratch. Various topics on creating a weapon will be discussed.

Getting Started

To get started, create a new .cpp file in the server project and call it weapon_myfirstweapon. Type this into your newly created file

#include "cbase.h"
#include "npcevent.h"
#include "in_buttons.h"

#include "c_hl2mp_player.h"
#include "hl2mp_player.h"

#include "weapon_hl2mpbasehlmpcombatweapon.h"

#ifndef CLIENT_DLL
#define CWeaponMyFirstWeapon C_WeaponMyFirstWeapon

Just to note something here, this tutorial expects the reader is using the Source SDK Multiplayer, but if the reader wanted to make the weapon singleplayer, it should be an easy fix.

Creating The Class

Now we will create the class that contains all the functions, so we can put the code in later. To start, make a new class, and define it like this

class CWeaponMyFirstWeapon : public CBaseHL2MPCombatWeapon

Now, open it up with some curly braces, and type this

  DECLARE_CLASS(CWeaponMyFirstWeapon, CBaseHL2MPCombatWeapon);



The code above just starts off the file, makes so it works with the server, and creates the base for the constructor.

Creating The Functions

After the line that says DEALRE_PREDICTABLE, type these functions in

void Precache(void);
void ItemPreFrame(void);
void ItemBusyFrame(void);
void ItemPostFrame(void);
void PrimaryAttack(void);
void AddViewKick(void);

virtual bool Reload(void);

virtual const Vector& GetBulletSpread(void)
    static Vector cone = VECTOR_CONE_1DEGREES;
    return cone;

#ifndef CLIENT_DLL

All this does is create stubs for the functions we will define later, with the exception of GetBulletSpread. To understand all of the functions, see Authoring a weapon entity, but the same things will be described later.

Creating Private Code

In this section, the reader will learn how to create variables, so they can be networked. To start off the private section, type

    CNetworkVar(float, m_flRateOfFire);

    CWeaponMyFirstWeapon(const CWeaponMyFirstWeapon &);

Basically, this just creates a variable, with the type of a float, called m_flRateOfFire, and creates an alternate constructor. To define m_flRateOfFire you can type

m_flRateOfFire = 0.4f; // 60 seconds divided by 150 shots (150 rpm) equals to 0.4

The same can also be done at the top of the file, with a #define.