const ray_length = 1000
func _input(event):
if event is InputEventMouseButton and event.pressed and event.button_index == 1:
var camera = $Camera
var from = camera.project_ray_origin(event.position)
var to = from + camera.project_ray_normal(event.position) * ray_length
But I wonder how can I get info about the object raycasted. I mean in the code above we cast a ray from one point and following a direction, but how do we know if the raycast is colliding with the object we want?
You are going to need to apply the “from” and “to” variables to a RayCast node
Make sure you add the a RayCast node to your scene first, and for simplicity set the enabled property to true in the inspector. Then connect to the node in your code and apply the variables. Example:
var raycast = get_node("/root/App/RayCast")
raycast.translation = from
raycast.cast_to = to
var collision_point = raycast.get_collision_point ( )
from here you will be able the determine the Vector3 of the collision, the colliding object, etc. Just reference to the docs from here. RayCast Docs
Note: its likely better to run the collision detection portion in the _physics_process(). But what I’ve provided should be a good start
Cool! I thought there was another way to achieve that (with the given script) without using the “Raycast” node.