Picking grid-aligned blocks using RayCast

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

I’m trying to implement a simple tile-based editor using RayCast. What I’m doing is simply performing a raycast from the mouse, and then flooring down the result:

func _physics_process(_delta):
  
  var mouse = get_viewport().get_mouse_position()
  
  translation = camera.project_ray_origin(mouse)
  cast_to = camera.project_ray_normal(mouse) * ray_length
  force_raycast_update()

  if is_colliding():
    target_position = get_collision_point().floor()
    target_normal = get_collision_normal().round()
    ghost.translation = target_position

The problem is that due to float imprecisions, the floored raycast result ends up jerking around a lot, and it’s generally quite annoying to place blocks as sometimes the result ends up being inside of my floor cube mesh.

Is there any fairly clean way I can solve this?

(moved to answers)

lqdev | 2021-01-25 10:07

:bust_in_silhouette: Reply From: lqdev

Alright, I figured it out:

target_position = (target_position + target_normal * epsilon).floor()

where epsilon is some small value like 0.01. This biases the selection a bit towards the normal of the selection, thus any fluctuations due to floating point error are mitigated.