RayCast and Mous

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

Hello people! I have a question for a strategy genre game. I need to make it so that when I hover the cursor over an object, I can click on it and some action takes place. I tried it on my own, but nothing happened. Or to be more precise, it turned out, but everything is fine in a certain zone, and then the RayCast flies and reaches the edge before the cursor. And I’m afraid that it won’t fit all permissions.

Here is my code that I tried:

extends Camera

onready var ray = $RayCast

func _input(e):
pass
if e is InputEventMouseMotion:
	pass
	ray.rotation.y -= e.relative.x * 0.0014
	ray.rotation.x -= e.relative.y * 0.0014

If anything, I put CSGBox on the end of RayCast to see its end

:bust_in_silhouette: Reply From: Regulus

Unfortunately, rotating the ray based off the event.relative does not quite work all around the screen, because the camera/screen pixels are not evenly spaced angularly like on a protractor. Instead, they are evenly spaced in a flat plane in front of the camera.

But you don’t really need to know the math behind it, because Godot has a function which does it for you:

The camera node comes with the function project_local_ray_normal(screen_position)
to get the vector which the mouse is pointing in.

To orient the RayCast to the correct direction, you could use look_at(position,up_direction) BUT this function only points the -Z side of the object towards the position, so make sure your ray’s cast_to property is in the direction Vector3(0,0,-1)

So for example:

extends Camera

onready var ray = $RayCast

func _input(e):
    if e is InputEventMouseMotion:
        ray.look_at(project_local_ray_normal(e.position), Vector3.UP)