how to reference a node from the mouse position

Godot Version

4.4

Question

I am in the early stages making a desktop tower defense type game just for fun.

I am using TileMapLayer for the map which, to start out, just has walkable ground and solid walls. I an using AStarGrid2d to have creeps move across the screen from left to right. I can place towers (add_child) by left clicking, causing the AStar path to update for each creep.

Now I want to right-click on a tower and remove it. How do I identify the correct child node that corresponds to the cell under my mouse cursor?

Thanks

1 Like

There are a few ways you could do this.

  1. You could nest a Control node under your tower, and then have that Control node react to your mouse clicks. This would act similarly to a collision box for the tower.
  2. Assuming you can only have 1 tower per grid cell, you could do some sort of lookup based on where you click to determine if a tower is within the grid cell.

I think #1 would be easier to implement.

1 Like

Regarding your #2 suggestion: do you mean like create a Dictionary or something that keeps track of where Towers are placed? Then if the cursor is over a tile containing a tower, I look up in the Dictionary or whatever to identify exactly which tower is on that tile. If this is what you mean, then, say I have 10 tower children added to the World scene. How do I reference for example ‘tower child number 6’ to queue_free() it?

Yes you could use a Dictionary or similar to store that information like that. You could free the node as you would normally, the Dictionary would just be used for quick lookup. However, for your use-case I think this would be more complicated then using a solution similar to #1.

Agreed. Thanks for your comments.