First-person shooter (FPS) is a genre in which a player uses a weapon and looks at the world through the eyes of a character. FPS games are extremely popular, as seen by the success of franchises such as
Call of Duty and
Battlefield .
Unreal Engine was originally created to develop FPS, so it is logical to use it to create such a game. In this tutorial you will learn the following:
- Create a Pawn with a first-person view that can move and look around
- Create weapons and tie them to player pawn
- Shoot bullets using direct tracing (also known as ray tracing)
- Damage the actors
Note: This article is the tenth part of a series of tutorials dedicated to the Unreal Engine:
Getting Started
Download the
project blank and unpack it. Go to the project folder and open
BlockBreaker.uproject . You will see the following scene:
')
The green wall consists of many goals. When they are dealt damage, they turn red. When their health reaches zero, they disappear. Red button re-sets all targets.
First you need to create a pawn player.
Making Pawn Player
Go to the
Blueprints folder and create a new
Blueprint Class . Select
Character as the parent class and name it
BP_Player .
Character is a type of Pawn, but with additional functionality, for example, with the
CharacterMovement component.
This component automatically handles movement, such as walking and jumping. We just call the appropriate function, so Pawn moves. In this component, you can also set variables, such as walking and jumping speeds.
To make Pawn move, we need to know when a player presses the movement key. To do this, we will tie the movement to the keys
W ,
A ,
S and
D.Note: If you are unfamiliar with bindings, you can read about them in the part of the tutorial on Blueprints . Key binding, we determine which keys will perform the action.
Creating motion bindings
Select
Edit \ Project Settings and open
Input settings.
Create two
Axis Mappings called
MoveForward and
MoveRight . MoveForward will drive forward and backward. MoveRight - moving left and right.
For
MoveForward, replace the key with
W. After that, create another key and select
S. Change the
Scale for
S to
-1.0 .
Note: If you want to learn more about the Scale field, read the Blueprints tutorial. The section " Axis value and input scale " says what it is and how to use it.
Later we will multiply the scale value by the forward pawn vector. This will give us a vector directed
forward with a
positive scale. If the scale is
negative , then the vector will be directed
backwards . With the help of the resulting vector it will be possible to move Pawn forward and backward.
Now we need to do the same for moving left and right. Change the key for
MoveRight to
D. Then create a new key and select A for it. Change
Scale for
A to
-1.0 .
Now that we have set up bindings, we need to use them for movement.
Implementation of the movement
Open
BP_Player , and then open Event Graph. Add a
MoveForward event (the one listed in the
Axis Events list). This event will be executed in each frame, even if you do not press anything.
It will also output an
Axis Value , which is equal to the
Scale values ​​previously specified. It will feed output
1 when you press
W and
-1 when you press
S. If you do not press the keys, then the output will be
0 .
Next you need to order the pawn to move. Add the
Add Movement Input and connect it as follows:
Add Movement Input will receive the vector and multiply it by the
Scale Value . This transforms it in the appropriate direction. As we use
Character , the
CharacterMovement component will move Pawn in that direction.
Now we need to specify the direction of movement. Since we want to move forward, we can use the
Get Actor Forward Vector . This will return the vector directed forward. Create it and connect as follows:
Summarize:
- MoveForward runs every frame and passes Axis Value to the output. This value will be equal to 1 when you press on W and -1 when you press on S. If you do not press any of these keys, then the output will be 0 .
- Add Movement Input multiplies the forward pawn vector by the Scale Value . Due to this, depending on the key pressed, the vector will be directed forward or backward. If you do not press the keys, the vector will have no direction, that is, the pawn will not move.
- The CharacterMovement component receives the result from the Add Movement Input , and then moves Pawn in that direction.
Repeat the process for
MoveRight , but replace
Get Actor Forward Vector with
Get Actor Right Vector .
To test the movement you need to set the default pawn in game mode.
Default pawn job
Click on
Compile and return to the main editor. Open the
World Settings panel and locate the
Game Mode section. Change the
Default Pawn Class to
BP_Player .
Note: if you do not have the World Settings panel, go to the Toolbar and select Settings \ World Settings .
Now when you start the game you will automatically use
BP_Player . Click on
Play and use the
W ,
A ,
S and
D keys to move through the level.
Now we will create bindings to rotate the head.
Creating overview bindings
Open
Project Settings . Create two more
Axis Mappings called
LookHorizontal and
LookVertical .
Replace the key for
LookHorizontal with
Mouse X.This binding will produce a positive value when you move the mouse
to the right , and vice versa.
Now change the key for
LookVertical to
Mouse Y.This binding will produce a positive value when you move the mouse
up , and vice versa.
Now we need to create logic to look around.
Implementation of the review
If Pawn does not have a
Camera component, Unreal automatically creates a camera for you. By default, the camera will use a rotation
controller .
Note: if you want to learn more about controllers, then study our tutorial " Artificial Intelligence ".
Despite the fact that the controllers are not physical, they still have their own turn. This means that you can direct the view of Pawn and the camera in different directions. For example, in a third-person game, the character and the camera do not always look in the same direction.
To rotate the camera in the game from the first person it is enough for us to change the rotation of the controller.
Open a
BP_Player and create a
LookHorizontal event.
To make the camera turn left or right, we need to adjust the
yaw (yaw) . Create an
Add Controller Yaw Input and connect it as follows:
Now when the mouse moves horizontally, the controller will turn left or right. Since the camera uses the rotation of the controller, it will also rotate.
Repeat the process for
LookVertical , but replace
Add Controller Yaw Input with
Add Controller Pitch Input .
If you start the game now, you will notice that the vertical movement of the camera is
inverted . This means that when you move the mouse
up, the camera will look
down .
If you prefer a non-inverted control, then multiply the
Axis Value by
-1 . This inverts the
Axis Value , which inverts the slope of the controller.
Click on
Compile and click
Play . Take a look around with your mouse.
Now that all the movement and review are ready, it's time to create a weapon!
Making weapons
Remember that when creating a Blueprint Class, you can choose a parent class? You can also choose your own Blueprints as parents. This is useful when there are different types of objects with common functionality or attributes.
Suppose we need to create different types of cars. You can create a base car class that contains variables such as speed and color. Then you can create classes (child) that will use the base class of the car as the parent. Each child class will contain the same variables. Now you have an easy way to create machines with different speeds and colors.
The same way you can create weapons. To do this, you must first create a base class.
Creating a base weapon class
Return to the main editor and create a
Blueprint Class of type
Actor . Call it
BP_BaseGun and open it.
Now we will create several variables defining the properties of the weapon. Create the following
float variables:
- MaxBulletDistance: the maximum range of each bullet
- Damage: the amount of damage caused by a bullet when hit by an actor
- FireRate: the gap (in seconds) between shots of bullets with weapons
Note: the default values ​​for all variables are zero, which is quite appropriate for a tutorial. However, if you want the new weapon classes to have a different default value, then you need to set it in BP_BaseGun .
Now we need a physical representation of this weapon. Add the
Static Mesh component and name it
GunMesh .
Don't worry about choosing a static mesh yet. We will deal with this in the next section, where we will create a child weapon class.
Creating a child class weapon
Click on
Compile and return to the main editor. To create a child class,
right-click on
BP_BaseGun and select
Create Child Blueprint Class .
Call it
BP_Rifle and open it. Open
Class Defaults and set the following values ​​to variables:
- MaxBulletDistance: 5000
- Damage: 2
- FireRate: 0.1
This means that the maximum path of each bullet will be equal to
5000 . If it hits the actor, it will deal
2 damage. When shooting bursts, the interval before each shot will be equal to not less than
0.1 seconds.
Now we need to specify the mesh that will be used by the weapon. Select the
GunMesh component and select
SM_Rifle for
Static Mesh .
Now the weapon is ready. Click on
Compile and close
BP_Rifle .
Now we will create our own camera component. He will give us more convenient control of the location of the camera. He will also allow us to attach the weapon to the camera so that it is always in front of the camera.
Camera creation
Open the
BP_Player and create the
Camera component. Call it
FpsCamera .
The default position is quite low, because of which the player may feel small. Change the
location of the
FpsCamera camera to
(0, 0, 90) .
By default, the Camera components do not use a controller rotation. To fix this, go to the Details panel and turn on
Camera Settings \ Use Pawn Control Rotation .
Now we need to set the place where the weapon should be.
Setting the weapon's location
We can use the
Scene component to create a weapon location. These components are ideal for setting locations because they contain only Transforms. Select
FpsCamera and create the
Scene component. This way it attaches to the camera. Call it
GunLocation .
Due to the fact that we have attached
GunLocation to
FpsCamera , the weapon will always maintain its position relative to the camera. Thus, we will always see the weapon in front of the camera.
Now assign the
location of the component
GunLocation values
(30, 14, -12) . So we will place the weapon in front and slightly to the side of the camera.
Then we set the
rotation values
(0, 0, -95) . When we attach the weapon, it will seem that it is always directed to the center of the screen.
Now we need to create a weapon and attach it to
GunLocation .
Creating and attaching weapons
Find the
Event BeginPlay and create a
Spawn Actor From Class . Set the
Class to
BP_Rifle .
Since we will need to use the weapon later, we will store it in a variable. Create a variable of type
BP_BaseGun and name it
EquippedGun .
It is important that the variable does not have type BP_Rifle , because the player can have different types of weapons, and not just one. If you create a different type of weapon, we will not be able to store it in a variable of type BP_Rifle . It will look like we are trying to shove a circle into a rectangular hole.
Choosing the BP_BaseGun type for a variable, we created a large “hole” suitable for many “shapes”.
Now set
EquippedGun to
Return Value Spawn Actor From Class .
To attach a weapon, we can use
AttachToComponent . Create it and set the
Location Rule and
Rotation Rule to
Snap to Target . Thanks to this, the weapon will have the same location and rotation as the parent.
Now create a link to
GunLocation and connect everything as follows:
Summarize:
- When creating a BP_Player, it will create an instance of BP_Rifle.
- EquippedGun will store the link to the created BP_Rifle for future use.
- AttachToComponent attaches a weapon to GunLocation
Click on
Compile and click
Play . Now, when creating a player, a weapon will be created! When cornering, the weapon will always be in front of the camera.
Now the fun begins: we will shoot! To check whether a bullet hit somewhere, we can use
direct tracing .
Shooting bullets
Tracing lines is a function that obtains start and end points (forming a line). She checks each point on a straight line (from beginning to end) until something hits it. In games for checking hit of a bullet, this method is most often used.
Since shooting is a weapon function, it must be performed in a weapon class, not a player. Open
BP_BaseGun and create a function
Shoot .
Then create two
Vector inputs and name them
StartLocation and
EndLocation . These will be the starting and ending points of the direct trace (which we will transmit from the
BP_Player ).
Tracing lines can be performed using
LineTraceByChannel . This node checks hits using a
Visibility or
Camera collision channel. Create it and connect as follows:
Now we need to check if the tracing of the lines falls into something. Create a
Branch and connect it like this:
When hit, the
Return Value will return
true and vice versa.
To give the player visual feedback on where the bullet hit, you can use the particle effect.
Creating bullet particles
First we need to get the location of the hit trace.
Drag Left Out Out on the graph. In the menu, select
Break Hit Result .
So we will create a node with different contacts related to the results of the direct trace.
Create a
Spawn Emitter at Location and set the
Emitter Template to
PS_BulletImpact . Then connect its
Location to the
Location of the Break Hit Result node.
Here is what it will look like:
Summarize:
- When performing a Shoot, it performs a straight line trace with the transmitted starting and ending point.
- If the hit is fixed, Spawn Emitter at Location will create a PS_BulletImpact at the hit point.
Now that the shooting logic is complete, we need to use it.
Call the function Shoot
First we need to create a key bindings for shooting. Click on
Compile and open the
Project Settings . Create a new
Axis Mapping called
Shoot . Select the
Left Mouse Button key for it and close the
Project Settings .
Then open the
BP_Player and create a
Shoot event.
To check whether the player presses the
Shoot key, it is enough for us to check whether the
Axis Value value is equal to one (
1 ). Create selected nodes:
Then create a link to
EquippedGun and call its function
Shoot .
Now we need to calculate the start and end points for tracing a straight line.
Calculate direct trace points
In many FPS the bullet flies from the camera, and not from the weapon. This is done because the camera is already perfectly aligned with the gun. Therefore, if we shoot from the camera, the bullet is guaranteed to fly to where the cursor is.
Note: some games still implement the shooting of weapons. However, for shooting exactly at the sight, additional calculations are required.
Create a link to
FpsCamera and connect it to
GetWorldLocation .
Now we need an end point. Do not forget that the weapon has a variable
MaxBulletDistance . This means that the end point must be at a distance of
MaxBulletDistance units from the camera. To implement this, create highlighted nodes:
Then connect everything as follows:
Summarize:
- When a player presses or holds the left mouse button , the weapon will fire a bullet with a starting point in the camera.
- The bullet will fly the distance specified in MaxBulletDistance
Click on
Compile and then on
Play . Hold down the
left mouse button to start shooting.
While the weapon shoots in each frame. This is too fast, so in the next stage we will reduce the frequency of firing weapons.
Reduced shooting frequency
First, we need a variable to determine if a player can shoot. Open
BP_Player and create a
boolean variable named
CanShoot . Set it to
true by default. If
CanShoot is
true , then the player can shoot, and vice versa.
Replace the
Branch section with the following:
Now the player can shoot only if the
Shoot key is pressed and the
CanShoot variable is
true .
Now add the selected nodes:
Changes:
- A player can shoot only when holding down the left mouse button , and when CanShoot is true
- When a player fires a bullet, the variable CanShoot is set to false . This will not allow the player to shoot again.
- CanShoot will be set to true again after the time specified in FireRate
Click on
Compile and close the
BP_Player . Click
Play and check the new shooting frequency.
Now we will teach the target and the button to respond to bullets. This can be done by adding
damage to them.
Damage application
Every actor in Unreal has the ability to take damage. However, you can choose for yourself
how the actor will react to it.
For example, a fighting game character will lose health when taking damage. However, some objects, such as a balloon, may not be healthy. Then you can program the ball so that it explodes when receiving damage.
In order to manage the damage the actor takes, we first need to apply the damage. Open
BP_BaseGun and add
Apply Damage at the end of the
Shoot function.
Now we need to specify which actor we want to do damage. In our case, this is the actor into which the direct trace falls. Connect the
Damaged Actor with the
Hit Actor node
Break Hit Result .
Finally, we need to specify the amount of damage done. Get the link to
Damage and connect it to
Base Damage .
Now, when you call
Shoot, it will cause damage to actors who are traced in a straight line. Click on
Compile and close
BP_BaseGun .
Now we need to process how the actor takes damage.
Damage handling
First we will process how the damage gets to the target. Open
BP_Target and create an
Event AnyDamage . This event is executed when the actor takes
non-zero damage.
Now call the
TakeDamage function and connect the
Damage pins. This will subtract health from the target's
Health variable and update the target color.
Now that the target takes damage, it loses health. Click on
Compile and close
BP_Target .
Now we need to handle how the button takes damage. Open the
BP_ResetButton and create an
AnyDamage event . Then call the
ResetTargets function.
This will restore all targets when taking damage with a button. Click on
Compile and close the
BP_ResetButton .
Click on
Play and start shooting at targets. If you want to restore the target, then shoot the button.
Where to go next?
The finished project can be downloaded
from here .
Although the FPS created in this tutorial is very simple, you can easily expand it. Try to create more weapons with different types of shooting frequency and damage. You can even try adding a recharge feature!