set_rotation not working inside input(event) but physics_process

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

I want my rigidbody to rotate every time i pressed input- (flap) which is key f. But not working here.

func _input(event):
	if event.is_action_pressed("flap"):
		rot+=10
		set_rotation(rot)

Working in:

func _physics_process(delta):
 rot+=10
 set_rotation(rot*delta)

There is no problem about taking input it just works fine. Just not setting rotation even if values changes after input(event) called. What is the reason? Thanks in advance.

:bust_in_silhouette: Reply From: Dlean Jeans

From the RigidBody2D’s description:

(…) You do not control a RigidBody2D directly. Instead you apply forces to it (gravity, impulses, etc.) and the physics simulation calculates the resulting movement based on its mass, friction, and other physical properties.

(…)

Note: You should not change a RigidBody2D’s position or linear_velocity every frame or even very often. If you need to directly affect the body’s state, use _integrate_forces, which allows you to directly access the physics state.


You can’t change the a RigidBody2D’s rotation anywhere outside of _integrate_forces. Even if you change it in _physics_process, it will jump back to its initial value after you release the key, that’s why you need a rot variable there.

To change the rotation, there are a few ways:

apply_torque_impulse():

func _input(event):
	if event.is_action_pressed('flap'):
		apply_torque_impulse(1000)

or:

func _integrate_forces(state):
	if Input.is_action_pressed('flap'):
		state.transform = Transform2D(rotation + 10, position)
		# or
		angular_velocity = 10