Hello,
One idea for this. You could start with four top-level nodes
- A MeshInstance called Wall with your wall mesh.
- A StaticBody called Floor. Add a MeshInstance as a child of Floor, and give this a new PlaneMesh. Then select this new MeshInstance and click (top-middle of screen) Mesh->Create Single Convex Collision Sibling
- A Spatial called BuildingManager with a GDScript attached.
- A Camera called Camera
BuildingManager could have script like (note: this isn't tested, might have typos...)
extends Spatial
onready var current_wall = $"../Wall".duplicate()
onready var camera = $"../Camera"
func _ready():
add_child(current_wall)
func _physics_process(var _delta : float):
var mouse_pos = get_viewport().get_mouse_position()
var from = camera.project_ray_origin(mouse_pos)
var to = from + camera.project_ray_normal(mouse_pos) * 1000.0
var result = get_world().direct_space_state.intersect_ray(from, to)
if not result.empty():
current_wall.translation = result.position
if Input.is_action_just_pressed("ui_accept"):
current_wall = $"../Wall".duplicate()
add_child(current_wall)
Should keep the wall following the mouse as you move the mouse over the floor, until you press whatever you have bound to "ui_accept" at which point it will "fix" the wall in place and spawn a new one, which can also then be placed, and so on...
You will probably need to adjust the translation.y after the ray-cast so that the Wall is not half-embedded in the floor. And then you might want to add the option to rotate the wall, and also to start snapping the position you get back from the ray-cast to a grid.
You then probably want to make Wall a StaticBody (like Floor), with its own MeshInstance and CollisionShape children. Otherwise your player character could run right through it. These Wall StaticBody instances might need to be on a different collision_layer
from Floor, which you could then exclude when you call intersect_ray
. Or not... it depends on if you want to be able to build walls-on-walls...
EDIT: BuildingManager Node -> Spatial
EDIT2: Add camera. Complete example at https://pastebin.com/Hs1ieHeg