Sunny Roh
Sunny Roh

Reputation: 21

How To Drag KinematicBody (3D) in Godot Engine

I am currently working on a game in which a player can stack a bunch of 3D objects, so I want to allow them to drag an object and place it on.

I have googled so many times how to drag/make an object to follow mouse cursor, but unfortunately I have not found the way to do it. If anyone knows how to do it, please let me know.

Here I attached my code. It detects the mouse position, but when I click on the screen the object moves in the up-right direction, not following the cursor at all.

extends KinematicBody

var velocity = Vector3()

const SPEED = 300 

func _physics_process(delta):
    if(Input.is_action_pressed("mouse_down")):

        var mouse  = get_viewport().get_mouse_position()

        print(mouse)

        var velocity = Vector3(mouse.x-get_translation().x,mouse.y-get_translation().y,0)

        velocity = velocity.normalized()*SPEED*delta

        velocity = move_and_slide(velocity, Vector3(0,1,0))

Upvotes: 2

Views: 5353

Answers (1)

magenulcus
magenulcus

Reputation: 400

Your code has multiple issues and maybe you should consider writing a 2D game first to get familiar with programming and godot before you start a 3D game, which is way more complex and frustrating.

However, to answer your question. Do you want the object to follow the mouse a bit delayed or do you want to have the object directly under the cursor. For the latter you just set the bodies position to the mouse position, like:

var mouse_pos  = get_viewport().get_mouse_position()
self.position = mouse_pos # The self is just for better understanding

If you want to have a slight delay in dragging the object, you must calculate the distance between the mouse and the object. Here is a possible solution:

func _physics_process(delta):
    if Input.is_action_pressed("mouse_down"):
        var mouse_pos  = get_viewport().get_mouse_position()
        var direction = mouse_pos - position
        move_and_slide(direction)

As I said, a 3d environment makes everything way more difficult since it is difficult get the right x,y and z position.

Furthermore, Godots math for vectors is very helpful and I really recommend you to read the documentation before you continue. This helps to keep your code as simple as possible.

Upvotes: 2

Related Questions