How can I create a Raycast between my camera and my mouse to move objects across a landscape

XPromusXPromus Posts: 2Member

I am working on a 3d city building game. So in order to build houses, I need to move them across the viewport with my mouse. The y - coordinate will always be 0 because the game will mostly take place on a plain. But for some reason, I can't get the raycast working. It detects a 3d coordinate but it is a very wrong one (but for some reason only on the z - axis). So if anyone knows how to create a mechanic which detects the point of the mouse in the 3d world I would love to read your answer :D


Tags :


  • kryzmakkryzmak Posts: 84Member

    Maybe this tutorial will help with your understanding:

    You have to convert coordinates from x/y viewport to the 3d environment. What I would use is using an Area node which detects collision point with a raycast from camera

  • TwistedTwiglegTwistedTwigleg Posts: 1,046Admin

    Have you seen the raycasting page in the Godot documentation? At the bottom of the page it has some example code on how to get the start and end positions for raycasting in 3D, so maybe that will help?

    I have used the code in the documentation several times and it has worked great for me.

  • XPromusXPromus Posts: 2Member

    Thanks for the quick reply :) . But somehow the from the Documentation outputs strange z values. They are always 250 or more. x although seems legit with values around -55 and 55. In the image, you can see the code I used. Maybe I made a mistake (btw my camera is set on orthographic)

  • TwistedTwiglegTwistedTwigleg Posts: 1,046Admin

    Looking at the code, I think one of the problems is that you are not changing the position of the Raycast node.

    Also, since you are using a Raycast node instead of using PhysicsDirectSpaceState, I you will need to change the to variable a little because Raycast nodes cast_to variable points relative to the position of the Raycast, while in PhysicsDirectSpaceState you need the positions in global space.

    Finally, you need to update the Raycast and set it out into 3D space with the changed variables, otherwise it will give you results based on the Raycast node's position, rotate, and scale in the last _physics_process call.

    I think the following code should work (but I have not tested it, so it may not work):

    var camera = get_node("Cambase/MainCamera")
    var raycast = get_node("Cambase/MainCamera/Raycast")
    var from = camera.project_ray_origin(event.position)
    var to = camera.project_ray_normal(event.position) * ray_length
    raycast.global_transform.origin = from
    raycast.cast_to = to
    Global.MousePos = Vector3(raycast.get_collision_point().x, 0, raycast_get_collision_point().z)
    print (str(Global.MousePos))
Sign In or Register to comment.