Help with raycasting in 4.1.3 C#
Asked Answered
S

2

0

Hi,

I'm trying to raycast and have the following function:

`public override void _Process(double delta)
{
PhysicsDirectSpaceState3D space_state = GetWorld3D().DirectSpaceState;
Vector2 mouse_position = GetViewport().GetMousePosition();
Camera3D camera = GetTree().Root.GetCamera3D();
Vector3 ray_origin = camera.ProjectRayOrigin(mouse_position);
Vector3 ray_end = ray_origin + camera.ProjectRayNormal(mouse_position) * 2000;
PhysicsRayQueryParameters3D rayParams = PhysicsRayQueryParameters3D.Create(from: ray_origin, to: ray_end);
Dictionary hit = space_state.IntersectRay(rayParams);

	GD.Print(hit.Keys);
	GD.Print(hit);
	
}`

The problem is that the print statements print nothing. The goal is to make an object look in the direction of mouse position.

Sallie answered 26/11, 2023 at 18:57 Comment(0)
B
1

Sallie The raycast will report a hit only if the mouse pointer is over a collider. Not sure how can that make an object look into mouse direction.

Briard answered 26/11, 2023 at 19:22 Comment(0)
S
0

Briard By getting the ray intersect position and rotating the object in that direction. Your first sentence helped me a lot, I added a StaticBody3D and a CollisionShape3D to my Mesh and now I am getting ray intersection position, thanks!

This is what I wanted to get and what I'm getting:

["position", "normal", "collider_id", "collider", "shape", "rid"]
{ "position": (1.616341, 0.135095, -0.084189), "normal": (0, 1, 0), "collider_id": 38788924720, "collider": StaticBody3D:<StaticBody3D#38788924720>, "shape": 0, "rid": RID(5557687681024) }

Sallie answered 26/11, 2023 at 19:49 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.