+1 vote

How can I achieve something like TargetJoint in Unity: https://www.youtube.com/watch?v=uG7doV7pT4I ?

There are some example at QA (I can't find it right now) but the problem with that method is grabing object only at origin point.


in Engine by (227 points)

1 Answer

+1 vote
Best answer

Maybe this can be done with a DampedSpringJoint2D somehow but here's a version using impulses applied to the RigidBody2D.

extends RigidBody2D

const DRAG_DIST = 64
const SPRING_FACTOR = 0.1
const DAMP_FACTOR = 0.01
var drag_point = Vector2()
var dragging = false

func _ready():

func _input(event):
    if event.type == InputEvent.MOUSE_BUTTON and !event.pressed and event.button_index == BUTTON_LEFT and dragging:
        dragging = false

func _input_event(viewport, event, shape_idx):
    if event.type == InputEvent.MOUSE_BUTTON and event.pressed and event.button_index == BUTTON_LEFT:
        drag_point = get_global_transform().xform_inv(event.pos)
        dragging = true

func _fixed_process(delta):
    if dragging:
        var tf = get_global_transform()
        var mouse_pos = tf.xform_inv(get_global_mouse_pos())
        var dist = drag_point.distance_to(mouse_pos)
        if dist > DRAG_DIST:
            var dir = mouse_pos - drag_point
            var dir_impulse = tf.basis_xform(dir.normalized())
            var impulse = dir_impulse * (dist - DRAG_DIST) * SPRING_FACTOR - get_linear_velocity() * DAMP_FACTOR
            apply_impulse(tf.basis_xform(drag_point), impulse)

You'll have to adjust the spring and damping factors and the dragging distance to your liking.

by (1,556 points)
selected by

Which method seems to works pretty well, thanks!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.