How to move RigidBody2D by an Input

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By bxgdo

Im new to godot, i try this and its working,

onready var pos = position
func _process(delta):

func move():
	pos += Vector2(10,0)

so i create _input and place move function, but it cant move by any input.

func _input(event):

print(event) show on output, and print(pos) from move function also increments every input, but the object still not move. so why?

:bust_in_silhouette: Reply From: Dlean Jeans

It’s recommended to use apply_central_impulse() and you should call it from _physics_process with an Input.is_action_pressed check:

func _physics_process(delta):

func move():
    if Input.is_action_pressed('ui_right'):
        apply_central_impulse(Vector2(10, 0))

This is incorrect. Impulses are for instantaneous forces, and should not be applied every frame. For continuous force, use add_force() - see below.

kidscancode | 2019-06-06 15:11

Ah yeah, in _integrate_forces() not in _physics_process(). I recall it works the same but might hurt performance.

Dlean Jeans | 2019-06-07 01:11

:bust_in_silhouette: Reply From: kidscancode

A rigid body cannot be moved directly, because it is controlled by the physics simulation. You move it by applying forces, not by changing its position.

In addition, any changes to the body’s physics state must be done in _integrate_forces(), not in _physics_process().

You can see an example here:

Physics Introduction: Using RigidBody2D

See the RigidBody2D documentation for details.

Thanks for the explanation,
i think for simple movement, object should use area2d or kinematicbody node.
Oh and, i follow your tutorials on youtube. Great work.

bxgdo | 2019-06-06 16:03

:bust_in_silhouette: Reply From: Zedonboy

Use set_axis_velocty().

var WALK_SPEED = 100

    func _physical_process(delay):
if Input.is_action_pressed("ui_right") :