How to convert mouse coordinates to 3d position?

inspired_coderinspired_coder Posts: 2Member
edited October 1 in 3D

I want to move 3d cube with mouse cursor, so i need convert mouse position for it. Can anyone help me?

Thanks in advance.

Answers

  • TwistedTwiglegTwistedTwigleg Posts: 109Member

    You’ll probably need to use raycasting to convert the mouse position to 3D space using a ray. Here’s a link to the documentation on raycasting which has some sample code that should help.

  • inspired_coderinspired_coder Posts: 2Member

    Yes, thank you, but there is not clear. I am using that function to get 3d world coordinates:

    camera.project_ray_normal(get_viewport().get_mouse_pos())

    ...but these coordinates cannot corresponds mouse position. Where is mistake?

  • TwistedTwiglegTwistedTwigleg Posts: 109Member
    Answer ✓

    This is the code that projects a Ray from the mouse coordinates

    var ray_lenght = 1000
    var mouse_pos = get_viewport().get_mouse_pos()
    var camera = get_node("camera")
    var from = camera.project_ray_origin(mouse_pos)
    var to = from + camera.project_ray_normal(mouse_pos) * ray_length
    

    Then you use those coordinates to raycast using intersect_ray in the direct space state.
    Something like this:

    var space_state = get_world().get_direct_space_state()
    # use global coordinates, not local to node
    var result = space_state.intersect_ray( from, to )
    

    Then you can do whatever you need with the results of the raycast.

Sign In or Register to comment.