Godot Version
4.3
Question
Hi :),
I’m making a turn-based strategy game and using the following code to update the variable ‘map_hit’ (the position on the map that the mouse is pointing at), using raycasts:
var origin = $Camera3D.project_ray_origin(mouse_pos)
var target = origin + $Camera3D.project_ray_normal(mouse_pos) * 1000
var space_state = get_world_3d().direct_space_state
var query = PhysicsRayQueryParameters3D.create(origin, target, 2)
var raycast = space_state.intersect_ray(query)
if raycast.size() > 0:
var hit_raw = raycast.position
var hit = Vector3(round(hit_raw.x), hit_raw.y, round(hit_raw.z))
map_hit = Vector3i(hit)
var map_array = Map.all_spaces[Vector2(round(hit_raw.x), round(hit_raw.z))]
var min_distance = 1000
for layer in range(map_array.size()):
if abs(map_array[layer] - hit.y) >= min_distance:
continue
map_hit.y = layer
min_distance = abs(map_array[layer] - hit.y)
else:
print("no collision")
#set map_hit to an arbitrary value where y is below 0
map_hit = Vector3i(0, -1, 0)
But when the camera gets far away from the map, the raycast becomes really inconsistent and doesn’t always detect collisions.
(I would upload a video to make it clearer, but it says new users can’t upload attachments…)
All maps are assigned a HeightMapShape3D when loaded and I’ve already checked that it’s set up correctly (including the collision layers).
Does anyone know what could be the problem?