0
\$\begingroup\$

I'm creating tank game demo , in game i want enemy tank to always face toward the player tank.

I already check look_at() function but it will face immediately, i don't want that. I want enemy tank to slowly rotate toward player.

What i'hv done so fare is :

MainWindow.gd

extends Node2D

func _ready():
    $Tank2.loadPlayer1($Tank1)
pass

enter image description here

EnemyTank.gd

extends KinematicBody2D

var rotSpeed = 0.3

var player1

var speed = 30
var velocity = Vector2()

func _ready():
pass

func loadPlayer1(obj):
    player1 = obj


func _process(delta):
    if player1 != null:
        velocity = Vector2()
        var rot_dir = (player1.position - position).angle()
        rotation += rotSpeed*rot_dir * delta
        velocity = Vector2(0,0).rotated(rotation)
        move_and_slide(velocity)
pass

My Result is : Enemy Tank (red) keep rotating

enter image description here

Does anyone know how do i fix this?

Thank you

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Those who are still locking for same answer, i manage to rotate enemy tank toward the player.

here is the code :

var turn_speed = deg2rad(3)

func _process(delta):
if player1 != null:
    var dir = get_angle_to(get_global_mouse_position())
    if abs(dir) < turn_speed:
        rotation += dir
    else:
        if dir>0: rotation += turn_speed #clockwise
        if dir<0: rotation -= turn_speed #anit - clockwise
pass

pass target position in place of get_global_mouse_position() to rotate toward.

Happy coding :)

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .