How to use raycasting

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

Hi guys! I’ve been trying to play with Raycasting following the Docs and I came across a doubt.
I was trying to do something similar to the code at the end of this page: Ray-casting — Godot Engine (3.0) documentation in English

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?

Thank you in advance! :slight_smile:

:bust_in_silhouette: Reply From: Adam Spruijt

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.

Thank you again! :slight_smile:

xpartano | 2019-02-14 09:41