If I remember how raycasting works correctly, then the following code should work:
extends Camera
const ray_length = 1000
var tree_scene = preload("res://src/models/Environment/Tree/adult_tree.dae")
var perform_raycast = false
func _physics_process(_delta):
if perform_raycast == true:
# Setup a Raycast
var ray_length = 1000
var mouse_pos = get_viewport().get_mouse_pos()
var camera = get_node("camera")
var from = camera.project_ray_origin(mouse_pos)
var to = from + camera.project_ray_normal(mouse_pos) * ray_length
var space_state = get_world().get_direct_space_state()
# Send the raycast into the scene and react if it collided with something
var result = space_state.intersect_ray(from, to)
# Make sure the raycast hit something...
if result.empy() != false:
# Make a new tree and set it's name
var clone_tree = tree_scene.instance()
clone_tree.name = "Tree"
# Sometimes I've had positioning issues if I set the
# position prior to calling add_child...
add_child(clone_tree)
# Change the position to the "position" key in the result dictionary.
#
# The position returned in the result dictionary is in world-space, so
# we need to set the global position of the newly created tree.
clone_tree.global_transform.origin = result["position"]
perform_raycast = false
func _input(event):
if Input.is_action_pressed("click"):
perform_raycast = true
I added a few things, like checking if the raycast hit something or not, but the majority of the code is still the same as in your initial post. I think the reason the code in your initial post was not working is because result
returns a Dictionary of data (documentation) from the raycast collision, so if you want the position, you need to use result["position"]
rather than just result
.
(Side note: Welcome to the forums!)