0 votes

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)))

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 lookat method, but since with RigidBodies you have to do it with setangular_velocity(), which I did with the help of code from docs (https://docs.godotengine.org/en/3.1/tutorials/physics/rigid_body.html)

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.

in Engine by (12 points)

1 Answer

0 votes
func _physics_process(delta):
    look_at(global_position + get_linear_velocity())
by (29 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.