How to create character-placeable items in game, such as buildings, furniture, etc.?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By iamstevie

Hey everyone,

I’ve been learning Godot for the last few months, absorbing every single tutorial I can find. One thing I haven’t been able to find much on is a way to create a system in which a user can “place objects” in a 2D world? This is a very common mechanic I’ve seen in games like Age of Empires, Forager, mobile games for creating buildings, etc.

Like let’s say you have a GUI that allowed you to select different buildings to add in your world and when you selected one of those buildings, you would see a slightly transparent image of your intended building wherever your cursor is. Then when you go to place it in your world, it would detect if there are any items in the way (such as trees, NPCs, etc.) and not allow you to place it.

My initial thought would be to do something like:

  1. Create a scene that contains all nodes for intended building
  2. When the player selects the building from the list, detect where the cursor is and then instance in the building into the world as well as a flag that’s “is_placable = false”
  3. Assuming the player is moving the item around in a “grid”, detect if there is any collision. This would probably be solved using an Area2D that detects if there are any trees, NPCs, other buildings underneathe where you want to place it.
  4. Once everything is “okay to place”, then enable an additional collision body that is a “StaticBody2D” so that it doesn’t move and other objects in the game can’t go through it (if it’s a building, let’s say)

There are probably a number of smaller details here I would consider, but would this be the best way to approach this? Has anyone found any tutorials or articles that discuss this kind of thing?

Sounds perfectly reasonable. :slight_smile:

njamster | 2020-03-05 12:19

This sounds reasonable, but I would consider also using state machines, just to make things more clear. For example, an icon on the menu could be actually a building in the Icon state. Then, when player clicks on it, duplicate it, and change state of that duplicate to InHand. Finally, when player decides to place it just change state to Placed.
Of course, this is only one way, but the concept of state machines can easily be applied to tons of things in game dev, and it makes your code much more transparent. I recommend checking out this video as a starting point.

kubaxius | 2020-03-06 13:40