A Gun with a Sliding Barrel

In the previous pose Creating a Gun we created a working gun. In this article we show how you can add a sliding barrel which moves backward every time the gun is fired.

The Barrel

In the gun we created, we included a cube for the barrel and a cylinder for the gun cylinder. We now want to have the barrel cube move backward while the cylinder stays fixed.

Because the barrel is a independent moving part of the gun, we need to define as a Rigidbody. As we are moving it using scripting and not using physics the Rigidbody should be set as Kinematic.

Kinematic Limitations

For moving the barrel we use Kinematic Limitations. This component can limited the movements of kinematic Rigidbodies in a custom way.

We want the barrel to only move in the Z direction, so we need to limit the X and Y local position to the range 0..0. This ensures that they cannot move in those local directions. For the Z-axis, we want the barrel to be able to move 5 cm (0.05 units) backwards, so we set the limitation to the range -0.05..0.

The range of motion is visible in the scene view as a blue line (for the Z-axis) with two blue spheres are the end. This lines represents the range along the barrel can move.

If we hit play now, you will be able to move the barrel transform manually in the scene view of with the inspector, but the barrel should always snap back to the defined range.

Animating the Barrel

You can now animate the barrel by setting a movement speed on the Kinematic Limitations. The barrel will then move in the desired direction until the limitation has been reached.

So we add another Method Call to the Gun Handle we created in the previous article to move the barrel in the forward direction with speed -1 when the trigger is pressed:

This will move the barrel backward when the gun is fired.

We now want the barrel to return to the original position again when it has moved backward completely. For this, we can use the Event Handler present on the Kinematic Limitations.

When the barrel reaches the end of the range (the end is the max value here, the start is the min value), it will start to Move the barrel forward with speed 0.1:

This will then automatically move the barrel forward again to return to the original position.

With this completed we have a gun with a recoiling barrel when it is fired.