Implement Arrow as a RigidBody2D

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

I want an arrow to look at trajectory of a flight as in real life. So, the first thing I tried was to just directly manipulate rotation of RigidBody with formula I found online:

velocity = get_linear_velocity()		
rotation = atan2(velocity.y, velocity.x)

This works visually just fine, but the collision shape doesn’t rotate, so as soon as it hits something, it bounces as if it wasn’t rotated. I soon found out that these kind of manipulations are not correct way to do things with RigidBodies.
Next thing I tried was to rotate the transform:

func _integrate_forces(state):
            ...
    	var m = state.get_transform()
		m.rotated(deg2rad(atan2(velocity.y, velocity.x)))
		state.set_transform(m)
            ...

This didn’t work at all, movement was chaotic, seems like transforms shouldn’t be applied every frame?

I think the right way to do this is to implement look_at method, but since with RigidBodies you have to do it with set_angular_velocity(), which I did with the help of code from docs (RigidBody — Godot Engine (3.1) documentation in English)

func look_follow(state, current_transform, target_position):
       var up_dir = Vector3(0, 1, 0)
       var cur_dir = current_transform.basis.xform(Vector3(0, 0, 1))
       var target_dir = (target_position - current_transform.origin).normalized()
       var rotation_angle = acos(cur_dir.x) - acos(target_dir.x)

       state.set_angular_velocity(up_dir * (rotation_angle / state.get_step()))
 func _integrate_forces(state):
        var target_position = $my_target_spatial_node.get_global_transform().origin
        look_follow(state, get_global_transform(), target_position)

I have trouble understanding how this works, but I think I managed to make this work in 2D (arrow looks at player). Now what should be target_position? How to make an arrow look at path it goes through? My understanding of transforms are weak.

:bust_in_silhouette: Reply From: Billy the Boy
func _physics_process(delta):
    look_at(global_position + get_linear_velocity())