Problem with rotations

Godot Version

Godot_V.4.3

Question

Its really hard to explain so i had to use recording. How do i make a sprite2D that is an body of enemy tank look in the direction where it is going.
I am using NavigationAgent2D.
Please help

meybe , you dont need to NavigationAgent2D .

just this code is enough.

var target :Vector2() #This is where you want it to look


# use a function here like :

func procces(delta):
    look_at(target)
1 Like

Sorry i didnt post video. This is what i meant, one sprite is looking at the player and the second sprite2D is body of the enemy.I want to body rotate based on direction of the PathFinding

I understand; but unfortunately I don’t know how to do it either; however I have an idea.
You can rotate the body based on speed and direction of movement , instead.

like:

var velo = Vector2(0,0)

...

if velo.x > 0 :
    rotation = 90
elif velo.x < 0 :
    rotation = -90
if velo.y > 0 :
    rotation = 180
elif velo.y < 0 :
    rotation = 0

and you can change numbers if this has issue

1 Like

I kind of complexified @zoopira’s last snippet, feel free to adapt this at your will. I still have to warn you that I wrote this purely based on what I understood in NavigationAgent2D — Godot Engine (stable) documentation in English and Vector2 — Godot Engine (stable) documentation in English.

extends ... class_name Enemy


...


@export var cannon_sprite: Sprite2D # the sprite from which the bullet appears
@export var body_sprite: Sprite2D # the "moving" part of the tank
@export var nav: NavigationAgent2D # for tracking next position
@export var old_direction := Vector2.RIGHT # change it to wherever the bot's facing initially, used only for the body


...


var target_pos: Vector2 # updated by your code, as the video shows, used only for the cannon


...


# Better than in _process, since we're handling rotations that could impact collisions, etc.
func _physics_process(delta: float) -> void:
    cannon_sprite.look_at(target_pos)
    var next_pos := nav.get_next_path_position()
    if next_pos != old_direction:
        var angle := old_direction.angle_to(next_pos)
        body_sprite.rotation += angle
        old_direction = next_pos
        

If rotation is done when needed but not how it is needed, maybe we’ll have to tweak the angle’s assignment to fix. Let me know how this works! ^^

1 Like

That works just fine, thanks guys for helping me out!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.