How to move an object with its current angle in 2D?

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

The old question seems outdated. I ask a new one
This the Player Bullet’s Code

extends KinematicBody2D
var pos=Vector2.ZERO
func _physics_process(delta):

it goes in hexagon line, not straight line. and get slower too because of closer distance

:bust_in_silhouette: Reply From: AndyCampbell

when moving a KinematicBody2D it’s not good practice to set the position directly, rather you should use move_and_slide or move_and_collide so you get the benefit of the collision detection.

There is an intro tutorial here

In your case you could do something like this

extends KinematicBody2D
var speed = 10
func _physics_process(delta):
    var vec_to_player = (GV.PlayerBullet.position - position).normalized()
    rotation = vec_to_player.angle()
    var collision = move_and_collide( vec_to_player * speed)
    if collision:
        print("Collided with ",

This calculates the vector from player and normalizes it, so that gives you a direction.
Then, from that direction you can set your rotation.
Multiply that vector by the speed to get a scaled velocity vector, and call move_and_collide
This will return a collision object if it collided, which you need to handle

I don’t know how your game will work, however this model will update the direction if the GV.PlayerBullet.position moves. If that’s not what you want, you need to store the vec_to_player and not update it each frame. Also, you might prefer move_and_slide to move_and_collide depending on your design. Check out the tutorial above for advice.

It worked for me, thanks

Echua36 | 2020-11-16 04:25