Attach actor to mouse cursor, place on click

I’m trying (and failing) to attach an actor to my mouse cursor. So when I press a key:

  1. The actor spawns and attaches to my mouse cursor, wherever it is hovering
  2. It always stays flat to the ground, so that it doesn’t go through walls/hover in the air.
  3. When I click, it places itself and stays put

When I was thinking it through, it seemed fairly straight forward sounding but I cannot figure this out. Any suggestions?

That’s quite a lot of logic to put in a single post, so ill try and give you a start.

In your actors tick, have a bool such as bIsBeingPlaced. Then a branch off it to where if its true, you update the actors location to be the mouses.

To keep it in the play field, and not go through walls, what I would do is create a nav mesh for your level. Normally, this is used for AI to navigate and see where it can walk, but what you can also use it for is during the updates to the actors location, constrain it to always be inside this mesh, but relative to the mouse.

If you look at the SillyGeo content example, the creator uses a similar idea for spawning his enemies. He uses the nav mesh as a “bounds” for where characters can spawn, so I recommend checking out that content example as well.

OnMouseClick would be where you could change that bool from being placed, to not.

Thanks for the advice.

I’ve now got it set up where it spawns and follows the mouse cursor pretty well. I’ve run into a few problems though and it’s driving me mad.

For one, Event Begin Play isn’t firing unless I have one of the objects in the scene. I don’t want it in the scene until you click the button to spawn one. I need the Event Begin Play to shoot off to enable input.

The event tick constantly runs to find the position like you said, and branch checks the bool you suggested. That works fine. However, if I try to branch check the bool elsewhere to do something else, the branch fails. Even when I made a different bool specifically for it. What is the event tick doing that is messing up a different branch?

For the first part, I would put it instead into OnActorSpawned.

This is called before BeginPlay is called, but after the components are initialized. If I remember correctly BeginPlay isn’t called until the actor is ready to tick, so this may be where you need to put it.

Below is the diagram of actor life cycle. A lot of the function names you see in the graph are for the C++ side of things, but the more solid boxes you may be able to make equivalent events for in the blueprints.

As for the tick, I am not sure. They should remain the same values, unless you have a broken reference, or you are not modifying the variable for that instance of the actor, but instead, for all actors of the class. Otherwise I am not sure, I would have to look at your graph to see why your tick is modifying the var.