RayCast3D Improperly rotating along with Area3D
Asked Answered
S

4

0

I'm using camera3d.project_ray to intersect with a rotated Area3D so I can place cubes on it with a mouseclick. But the placement is rotating away with the Area3D as shown in the GIF.

code:


var cube = preload("res://cube.tscn")

func _process(delta: float) -> void:
	if Input.is_action_pressed("ui_left"):
		$Area3D.rotation.y += delta
	if Input.is_action_pressed("ui_right"):
		$Area3D.rotation.y -= delta
		
func _input(event: InputEvent) -> void:
	if is_left_click(event):
		var world_pos = get_world_intersect_pos()
		if world_pos == Vector3.ZERO:
			return
		var new_cube = cube.instantiate()
		new_cube.position = world_pos
		find_child("cubes").add_child(new_cube)

func get_world_intersect_pos() -> Vector3:
	var space_state = get_world_3d().direct_space_state
	var cam = $Camera3D
	var mousepos = get_viewport().get_mouse_position()
	var origin = cam.project_ray_origin(mousepos)
	var end = origin + cam.project_ray_normal(mousepos) * 1000
	var query = PhysicsRayQueryParameters3D.create(origin, end)
	query.collide_with_areas = true
	var result = space_state.intersect_ray(query)
	if "position" in result:
		return result["position"]
	else:
		return Vector3.ZERO
		
func is_left_click(event: InputEvent) -> bool:
	return event is InputEventMouseButton and event.pressed and event.button_index == MOUSE_BUTTON_LEFT

version: v4.2.1.stable.official [b09f793f5]

Shiff answered 24/2 at 13:19 Comment(0)
E
0

Shiff have you debugged this line to make sure the math is handling this right? Sounds like a calculation is off somewhere.

var end = origin + cam.project_ray_normal(mousepos) * 1000
Emigration answered 24/2 at 19:21 Comment(0)
S
0

Emigration no I'm not sure if that's it. The raycast works fine, it's just the part where the cubes are added as a child to the rotated area3d. For example, if the $cubes node is a child of $main instead of $Area3D, the cubes are instantiated in the correct location - they just don't rotate at all of course.

Shiff answered 24/2 at 20:7 Comment(0)
A
0

Shiff
You're assigning world position to cube's local position property. Try assigning to world (global) position instead.

var new_cube = cube.instantiate()
find_child("cubes").add_child(new_cube)
new_cube.global_position = world_pos
Alpine answered 24/2 at 21:33 Comment(0)
S
0

Alpine that works great, thanks!

Shiff answered 25/2 at 16:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.