Why _integrate_forces doesn't work get RigidBody2D has Gravity Scale set to 0?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By waqleh
:warning: Old Version Published before Godot 3 was released.

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.

From the docs :

void set_linear_velocity ( Vector2 linear_velocity )
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 apply_impulse() and state.integrate_forces();

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(relative_x) > abs(relative_y):
relative_y=0
else:
relative_x=0

target = vector2(relative_x,relative_y)

apply_impulse(Vector2 offset,target)

state.integrate_forces()

IKRadulov | 2017-07-22 11:43