How can I get which face normal hit with raycast?

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

Assuming the collision shape is a simple cube, how can I detect which surface is hit using a raycast?

For example if the raycast hit the top face, it should give me Vector3(0, 1, 0) as result.

Is there any helper function for this?

:bust_in_silhouette: Reply From: unlut

If you are performing raycast from the script, intersect_ray function returns exactly what you are looking for. Here is an example with mouse click:

func _input(event):
	if event is InputEventMouseButton and event.is_pressed():
		var worldspace = get_world_3d().direct_space_state
		var start = camera.project_ray_origin(event.position)
		var end = camera.project_position(event.position, 1000)
		var params = PhysicsRayQueryParameters3D.new()
		params.from = start
		params.to = end
		var result = worldspace.intersect_ray(params)
		if (result != null and result.size() > 0):
			print(result["normal"])

Thanks! It was an exact answer for me…

thebluetropics | 2023-02-01 01:55

1 Like