How to get RigidBody2D linear acceleration

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

I’m getting the acceleration of my RigidBody2D this way (it work):

func _process(_delta):
    calc_acceleration()

func calc_accelerations():
	var v0 = linear_velocity
	var r0 = angular_velocity
  	var dt = 0.1
  	yield(get_tree().create_timer(dt), "timeout") #wait for dt seconds
  	var v1 = linear_velocity
  	var r1 = angular_velocity
    	
  	acc = (v1 - v0)/dt    #dv/dt
    racc = (r1 - r0)/dt   #dTheta/dt

But the yield() induce lots of errors when my RigidBody2D is deleted from the scene. I use queue_free() to delete it.

Is there a clean way of accessing the acceleration ?
I tried putting a Timer child but it didn’t worked with small delay

:bust_in_silhouette: Reply From: njamster

Any reason why you don’t simply use the delta-argument provided to _process?

var v0
var r0

func _process(delta):
	if v0 and r0:
		var acc  = (linear_velocity  - v0) / delta
		var racc = (angular_velocity - r0) / delta
	v0 = linear_velocity
	r0 = angular_velocity

thanks, I didn’t thought about using delta

I just had to put it in _physics_process() and it worked perfectly

leo-pnt | 2020-05-02 20:10

Can someone explain why (linear_velocity - v0) is not 0 ? It should be zero right because v0 is also linear_velocity of the same frame.

Kushal | 2022-01-12 12:29

v0 is actually the linear_velocity of the previous frame in this context if I understood correctly

leo-pnt | 2022-01-12 12:40

Yes, it should be the linear velocity of the previous frame as per the acceleration formula goes, but how do we assign v0 the linear velocity of the previous frame, I am scratching my head over this long time

Kushal | 2022-01-14 00:44

Let’s say linear_velocity increases by 1.0 every frame,

Frame |  v0  | linear_velocity | v0 = linear_velocity
___________________________________________________
0     |  0.0 | 0.0             | 0.0
1     |  0.0 | 1.0             | 1.0
2     |  1.0 | 2.0             | 2.0
3     |  2.0 | 3.0             | 3.0
...

So you calculate acceleration with v0 and linear_velocity then prepare v0 for the next frame

leo-pnt | 2022-01-14 13:36