Godot Version
4.3
Question
So, I have a large cube that my camera rotates around. I want to cast a ray from the mouse position on the screen and straight away from camera. I can get the mouse position, but I dont know how to get the direction to cast the ray.
There maybe a better way to do this. Why I want this is because I want the player to be able to place objects on the cube. I want the objects to be selected and then follow the mouse around along the surface of the cube until the player places them. However, I don’t know how to get the location on the cube relative to mouse position projected from camera in order to place/move the object.
The following is my implementation:
func get_collider_data() -> Dictionary:
var mouse_pos: Vector2 = viewport.get_mouse_position()
_ray_query_parameters.from = camera.camera.project_ray_origin(mouse_pos)
_ray_query_parameters.to = _ray_query_parameters.from + camera.camera.project_ray_normal(mouse_pos) * MAX_RAY_LENGTH
return direct_space_state.intersect_ray(_ray_query_parameters)
The direct_space_state is the following:
var direct_space_state: PhysicsDirectSpaceState3D = camera.get_world_3d().direct_space_state
and the ray_query_parameters are “PhysicsRayQueryParameters3D”
Thanks, I used what you had as a base, and instead of using the actual built in ray from the camera I used its methods in combination with the RayCastNode.
Here is the code I ended up doing if you are curious.
func _physics_process(_delta: float) -> void:
if follow_mouse:
var mouse_pos : Vector2 = get_viewport().get_mouse_position()
var from : Vector3 = camera.project_ray_origin(mouse_pos)
var to : Vector3 = from + camera.project_ray_normal(mouse_pos) * RAY_LENGTH
ray.position = from
ray.set_target_position(to)
ray.force_raycast_update()
var set_pos : Vector3 = snapped(ray.get_collision_point(),Vector3(2,2,2))
if abs(set_pos.x) == 10:
if set_pos.x == 10:
current_item.position = set_pos + Vector3(1,0,0)
else:
current_item.position = set_pos - Vector3(1,0,0)
elif abs(set_pos.y) == 10:
if set_pos.y == 10:
current_item.position = set_pos + Vector3(0,1,0)
else:
current_item.position = set_pos - Vector3(0,1,0)
else:
if set_pos.z == 10:
current_item.position = set_pos + Vector3(0,0,1)
else:
current_item.position = set_pos - Vector3(0,0,1)
1 Like