Shooting Implementation

Now that our character is ready, let's implement shooting, add shooting controls, and use raycasting (intersections) to check if the bullet hits the target.

  1. In the Asset Browser, double-click CharacterMotion.agraph and enter the main_sm state machine.
  2. Add a new State node, rename it to shoot, and open its internal graph.
  3. In the Anim field of the Animation Player node, select the data/fps/hands/hands_animations/hands_pistol_shoot.anim file, change the Speed value to 30, and disable looping.

  4. Click Save and Navigate Back to go back to the state machine editor (you can also do it via the Graph Hierarchy window or using the breadcrumb bar).

  5. Now let's add a transition from locomotion to the shooting state. Hover over the edge of the locomotion node until a connection handle appears, then drag it to the shoot node and release. The editor automatically creates a Condition node between them. This node holds the transition settings and determines when it fires.

    Select the newly created condition node and rename to is_shooting. Change its Duration value to 0.05.

  6. Enter the is_shooting node inner graph. In the Graph Parameters window, create a new variable of the Trigger type named shoot, drag it into the canvas, and connect to the Transition Result node.

    Click Save and Navigate back to return to the state machine editor. Now we can see the locomotion and shooting animations blend as we change move_x, move_y, and click the Trigger button in the Graph Parameters window. However, now the animation only goes from locomotion to shoot, with no way back. We need to add return logic.

  7. Inside the main_sm graph, add another transition - from shoot back to locomotion. This will create one more Condition node. Name it end_shooting and double-click to open its inner graph.

    If we let the shooting animation play all the way to the end, the firing rate will be limited because we would have to wait for it to finish before shooting again. To avoid that, we will only use the first part of the animation. Based on the preview, it starts transitioning back to idle at around 40% playback. We'll use an Anim Time Fraction node to cut it at that point and return to locomotion, so we can trigger the next shot much sooner.

    Let's add an Anim Time Fraction node and a Greater node inside the end_shooting condition. Connect the Anim Time Fraction output to input A of Greater, set input B to 0.4, and connect the Greater output to the Transition Result node. Click Save.

    Now the state will transition back to locomotion after 40% of the shooting animation. However, we want to be able to interrupt the firing cooldown and trigger the locomotion-to-shooting transition at any time a shot is fired. To do that, in the main_sm graph, select the end_shooting condition, enable the Can be interrupted flag in the Graph Parameters window, and click Save.

If everything is done correctly, the result should look like this:

You can push the firing rate even further by adding a self-transition on the shoot state. Add a new Condition node and name it shoot_loop. Create a transition from shoot to this node, and another transition back to shoot. In the shoot_loop node nested graph, use the trigger we created earlier.

Shooting Controls#

Let's implement a new component for checking if the fire button is pressed. This is the preferred way as we are going to use this logic in the other components:

  • In the HandAnimationController component to start the shooting animation.
  • In the WeaponController component to start the shooting logic.

In this component, you can also define a button that acts as a fire button.

To handle user input, use one of the Input class functions to check if the given button is pressed.

  1. Create the ShootInput component and copy the following code to it.

    ShootInput.h

    Source code (C++)
    
    #pragma once
    #include <UnigineComponentSystem.h>
    class ShootInput :
        public Unigine::ComponentBase
    {
    public:
    	COMPONENT_DEFINE(ShootInput, Unigine::ComponentBase);
    
    	bool isShooting();
    };
    						

    ShootInput.cpp

    Source code (C++)
    
    #include "ShootInput.h"
    REGISTER_COMPONENT(ShootInput);
    using namespace Unigine;
    using namespace Math;
    
    bool ShootInput::isShooting()
    {
    	// return the current state of the LMBUTTON and check mouse capture on the screen
    	return Input::isMouseButtonDown(Input::MOUSE_BUTTON_LEFT) && Input::isMouseGrab;
    }
    						

    Save the files, build and run the application by hitting Ctrl + F5 to make the Component System generate a property.

  2. In the Editor, add the ShootInput property to the player Dummy Object.

  3. Modify the HandAnimationController component in order to use logic of the ShootInput. Replace your current code with the following one:

    HandAnimationController.h

    Source code (C++)
    
    #pragma once
    #include <UnigineComponentSystem.h>
    #include <UnigineGame.h>
    #include "FirstPersonController.h"
    ${#HL}$#include "ShootInput.h"${HL#}$
    class HandAnimationController :
        public Unigine::ComponentBase
    {
    public:
    	COMPONENT_DEFINE(HandAnimationController, Unigine::ComponentBase);
    
    	PROP_PARAM(Node, player_node, nullptr);
    
    	// declare methods to be called at the corresponding stages of the execution sequence
    	COMPONENT_INIT(init);
    	COMPONENT_UPDATE(update);
    
    	Unigine::Math::vec2 getLocalMovementVector();
    ${#HL}$	void shoot();${HL#}$
    
    protected:
    	// world main loop overrides
    	void init();
    	void update();
    
    private:
    	FirstPersonController *fpsController = nullptr;
    ${#HL}$	ShootInput * shootInput = nullptr;${HL#}$
    
    	Unigine::NodeSkeletonPosePtr pose = nullptr;
    	Unigine::AnimScriptPtr animScript = nullptr;
    };
    						

    HandAnimationController.cpp

    Source code (C++)
    
    #include "HandAnimationController.h"
    
    REGISTER_COMPONENT(HandAnimationController);
    using namespace Unigine;
    using namespace Math;
    
    Unigine::Math::vec2 HandAnimationController::getLocalMovementVector()
    {
    		return Math::vec2(
    			Math::dot(fpsController->getSlopeAxisY(), fpsController->getHorizontalVelocity()),
    			Math::dot(fpsController->getSlopeAxisX(), fpsController->getHorizontalVelocity())
    		);
    }
    void HandAnimationController::init()
    {
    	fpsController = ComponentSystem::get()->getComponent<FirstPersonController>(player_node);
    
    ${#HL}$	shootInput = ComponentSystem::get()->getComponent<ShootInput>(player_node);${HL#}$
    
    	// get the node that this component is assigned to and cast it to NodeSkeletonPose type
    	pose = checked_ptr_cast<Unigine::NodeSkeletonPose>(node);
    
    	// get the animation control script
    	animScript = pose->getAnimScript();
    }
    
    ${#HL}$void HandAnimationController::shoot()
    {
    	// set the shooting trigger in the animation
    	animScript->setParamTrigger("shoot", true);
    }${HL#}$
    
    void HandAnimationController::update()
    {
    	// update movement vector in animation parameters
    	vec2 movementVector = getLocalMovementVector();
    	animScript->setParamFloat("move_x", movementVector.y);
    	animScript->setParamFloat("move_y", movementVector.x);
    
    ${#HL}$	// input handling: check if the 'fire' button is pressed
    	if (shootInput->isShooting())
    		shoot();${HL#}$
    }
    						

Using Raycasting#

To implement shooting, you can use the properties of the PlayerDummy camera. This camera has its -Z axis pointing at the center of the screen. So, you can cast a ray from the camera to the center of the screen, get the intersection, and check if you hit anything.

In the component code below, we will store two points (p0, p1): the camera point and the point of the mouse pointer. getIntersection() method will cast a ray from p0 to p1 and check if the ray intersects with any object's surface (that has the matching Intersection mask to restrict the check results). If the intersection with such surface is detected, the method returns the hitObject and hitInfo values (the intersection point and normal).

  1. Create a WeaponController component and copy the following code:

    WeaponController.h

    Source code (C++)
    
    #pragma once
    #include <UnigineComponentSystem.h>
    #include <UnigineVisualizer.h>
    #include "ShootInput.h"
    
    class WeaponController :
        public Unigine::ComponentBase
    {
    public:
    	COMPONENT_DEFINE(WeaponController, Unigine::ComponentBase);
    
    	PROP_PARAM(Node, shooting_camera, nullptr);
    	PROP_PARAM(Node, shoot_input_node, nullptr);
    
    	Unigine::PlayerDummyPtr shootingCamera = nullptr;
    	ShootInput *shootInput = nullptr;
    	int damage = 1;
    
    	// Intersection mask to define objects to be affected by bullets
    	int mask = ~0;
    
    	// declare methods to be called at the corresponding stages of the execution sequence
    	COMPONENT_INIT(init);
    	COMPONENT_UPDATE(update);
    
    	void shoot();
    
    protected:
    	// world main loop overrides
    	void init();
    	void update();
    };
    						

    WeaponController.cpp

    Source code (C++)
    
    #include "WeaponController.h"
    REGISTER_COMPONENT(WeaponController);
    using namespace Unigine;
    using namespace Math;
    
    void WeaponController::shoot()
    {
    
    	// set the line starting point (p0) in the camera position and end point (p1) in the point 100 units away in the camera view direction
    	Vec3 p0 = shootingCamera->getWorldPosition();
    	Vec3 p1 = shootingCamera->getWorldPosition() + (Vec3)shootingCamera->getWorldDirection() * 100;
    
    	// create an intersection-normal storage object
    	WorldIntersectionNormalPtr hitInfo = WorldIntersectionNormal::create();
    	// get the first object intersected by the (p0,p1) line
    	Unigine::ObjectPtr hitObject = World::getIntersection(p0, p1, mask, hitInfo);
    	// if the intersection is found
    	if (hitObject)
    	{
    		// render the intersection normal to the surface in the hit point using Visualizer
    		Visualizer::renderVector(hitInfo->getPoint(), hitInfo->getPoint() + (Vec3)hitInfo->getNormal(), vec4_red, 0.25f, false, 2.0f);
    	}
    }
    
    void WeaponController::init()
    {
    	// getting the camera to which the ShootInput component is assigned
    	shootingCamera = checked_ptr_cast<Unigine::PlayerDummy>(shooting_camera.get());
    
    	// getting the ShootInput component from the 'shoot_input_node' node
    	shootInput = ComponentSystem::get()->getComponent<ShootInput>(shoot_input_node.get());
    }
    
    void WeaponController::update()
    {
    	// handle user input: check if the 'fire' button is pressed
    	if (shootInput->isShooting())
    		shoot();
    }
    						

    Save all the files that we modified and then build and run the application by hitting Ctrl + F5 to make the Component System update properties used to assign the components to nodes. Close the application after running it and switch to UnigineEditor.

  2. Add the component to the player Dummy Object.
  3. Assign PlayerDummy to the Shooting Camera field so that the component could get information from the camera.
  4. Assign the player Dummy Object to the Shoot Input field.

To view the bullet-surface intersection points and surface normals in these points, you can enable Visualizer when the application is running:

  1. Open the console by pressing ~
  2. Type show_visualizer 1

The information on this page is valid for UNIGINE 2.22 SDK.

Last update: 2026-09-11 03:51:46