You may have noticed that you don’t see native events on your actors to detect left/right click event listeners. You could consider potentially adding something like a Cylinder mesh around your character mesh, or use your character mesh itself and utilize the ‘On Clicked’ events:
(If you have a modular character like this, use the capsule component or an invisible cylinder instead for example if using this technique).
This is a really straightforward technique if all you need is a left click event listener.
There is no native approach here for a right click event listener, so instead we’re going to implement one manually, which will utilize the Player Controller class instead.
Let’s explore how we can get both, left and right click events captured on our actor using the player controller and ray tracing.
Capturing event using Player Controller
You should probably already have a Player Controller class and if not, you can create a new blueprint which extends the player controller and make sure that you use it in your game mode/world settings.
This is what we’re going to be implementing:
Note that the Event Dispatchers are optional. I use them for things like widget event listeners, particularly to confirm where mouse is released for example, as widget event handlers are not always reliable.
So the important function from here for you to consider is Get Target Under Mouse Click
which is:
This function uses the Get Hit Result Under Cursor by Channel function in order to identify whether when click occurs, the mouse is over an actor.
After this, you can see that I check whether the actor implements an Interface.
So we’re going to create this interface and add it to any actor that you want to enable this functionality to.
Adding basic interface
To create and use an interface is quite simple. In your content browser right click and search for ‘interface’.
As you can see, I created my interface called BPI_Interactable.
This interface exposes 2 simple functions:
On Left Clicked and On Right Clicked.
Next, you want to add it to your actor class(es). I have a base class which is used by all my players and mobs, therefore I just need to add it once to this parent class.
After adding this, if you go to the Functions section and click Override you should find the new functions exposed there:
Now, simply implement your event click listener as you desire!
For example, this is what I’ve put:
You can see that if I left click, I request that my Actions Component will handle the Select Target function (this used to be done via click listener on capsule).
When I right click, I simply print a log, but I will change that to either default attacking actor or perhaps to open menu to trade and add to party etc.
Simply test it now and you should find you will get the logs as expected!