Godot Version
4.3-stable
Question
I have a Gridmap with a MeshLibrary, I’m firing a raycast from the camera to my mouse position and it’s hitting the Gridmap and returns the cell data but not returning the “Tile” it’s hitting properly. It’s returning -1 which is basically empty
But it’s showing the rest of the data fine , so I think I’m pulling the wrong data or the raycast itself is incorrect? I’m not 100% sure.
The end goal is to turn the grass into snow on click
extends GridMap
const GRASS_TILE_ID = 41
const SNOW_TILE_ID = 83
func _input(event):
if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
print("Mouse click detected")
var camera = get_viewport().get_camera_3d()
var from = camera.project_ray_origin(get_viewport().get_mouse_position())
var to = from + camera.project_ray_normal(get_viewport().get_mouse_position()) * 1000
print("Raycast origin: ", from)
print("Raycast direction: ", to)
var ray_params = PhysicsRayQueryParameters3D.new()
ray_params.from = from
ray_params.to = to
ray_params.collision_mask = 1
var space_state = get_world_3d().direct_space_state
var result = space_state.intersect_ray(ray_params)
if result:
print("Raycast hit something!")
print("Result: ", result)
print("Hit position: ", result.position)
print("GridMap Cell Size: ", cell_size)
var cell = local_to_map(result.position)
print("Converted grid position: ", cell)
var current_tile_id = get_cell_item(cell)
print("Tile ID found: ", current_tile_id)
if current_tile_id == GRASS_TILE_ID:
print("Tile is grass. Changing to snow.")
set_cell_item(cell, SNOW_TILE_ID)
elif current_tile_id == SNOW_TILE_ID:
print("Tile is snow. Changing to grass.")
set_cell_item(cell, GRASS_TILE_ID)
else:
print("Tile ID doesn't match grass or snow. Tile ID found: ", current_tile_id)
else:
print("Raycast didn't hit anything.")
I essentially want to click the tile, get the type of mesh it is and if it’s grass, turn it to snow, but I can’t for the life of me get it to work and I wonder if the issue is the raycast but then it says it’s returning correctly, it’s just the contents it can’t find:
Mouse click detected
Raycast origin: (-1, 17, 8)
Raycast direction: (31.73623, -885.0504, -422.3875)
Raycast hit something!
Result: { “position”: (-0.442934, 1.649989, 0.676182), “normal”: (0, 1, 0), “face_index”: -1, “collider_id”: 41288729800, “collider”: GridMap:<GridMap#41288729800>, “shape”: 0, “rid”: RID(15801184681984) }
Hit position: (-0.442934, 1.649989, 0.676182)
GridMap Cell Size: (1, 0.1, 1)
Converted grid position: (-1, 16, 0)
Tile ID found: -1
Tile ID doesn’t match grass or snow. Tile ID found: -1