+1 vote

I am trying to drag and drop a RigidBody2D, however I have noticed that my code doesn't work at all if I set the Gravity Scale = 0 and if I set the Gravity Scale to 0.5 it works however if I drag it and stop moving the mouse for a second, it gets stuck in its place as if I did set the Gravity Scale to 0.

extends RigidBody2D

var is_held = false
func _ready():
    set_process_input(true)

func _integrate_forces(state):
    var lv = state.get_linear_velocity()

    if is_held:
        lv = (get_viewport().get_mouse_pos() - get_pos()) * 16

    state.set_linear_velocity(lv)

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

func _on_food_input_event( viewport, event, shape_idx ):
    if event.type == InputEvent.MOUSE_BUTTON and event.pressed and event.button_index == BUTTON_LEFT:
        is_held = true

In the end what I am trying is to be able to drag and drop the rigid body either vertically or horizontally and not both nor diagonal.

in Engine by (18 points)
edited by

From the docs :

void setlinearvelocity ( Vector2 linearvelocity )
Set the body linear velocity. Can be used sporadically, but DON’T SET THIS IN EVERY FRAME, because physics may be running in another thread and definitely runs at a different granularity. Use _integrate
forces as your process loop if you want to have precise control of the body state.
You should use applyimpulse() and state.integrateforces();

This should be the main reason that it won't work.

Also for locking on to an axis while moving you can get mouse relative position from previous one. and check wheather the x pos or y pos is bigger . Then nullify the smaller position. like so :

if abs(relativex) > abs(relativey):
relativey=0
else:
relative
x=0

target = vector2(relativex,relativey)

apply_impulse(Vector2 offset,target)

state.integrate_forces()

Please log in or register to answer this question.

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 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 webmaster@godotengine.org with your username.