0 votes

I'm trying to make a gun that shoot a bullet that slowly turns back towards the player... But it only seems to get stuck in one spot with it direction spinning around "randomly" I tried a bunch of things but haven't had much luck... suggestions? I mostly curious on how I can lerp its angle specifically... but as an alternative I think I could just have a vector that slowly move towards the player maybe..

Shooting code:

if Input.is_action_just_pressed("shoot") and has_gun:
    var inst : Bullet = ld_bullet.instance()
    inst.dir = rotation
    inst.spawn_pos = muzzle.global_position
    add_child(inst)

Bullet code:

class_name Bullet
extends Area2D
var spawn_pos
var dir = 0 
var target_player = false

func _ready():
    print(dir)
    set_as_toplevel(true)
    global_position = spawn_pos

func _process(delta):
    if target_player:
        var dir_to_player = global_position.angle_to(Master.player.global_position)
        dir = lerp_angle(dir, dir_to_player, 1)
        print("lerp ", dir)
    var motion = Vector2(5,0).rotated(dir)
    position += motion

func _on_TimerTurn_timeout():
    target_player = true

thanks for reading (:

in Engine by (25 points)

1 Answer

0 votes

Here's what I think will work but haven't tested:

extends Area2D
class_name Bullet

var spawn_pos
var dir = 0 
var target_player = false

var speed = 500
var velocity = Vector2.ZERO

func _ready():
    print(dir)
    set_as_toplevel(true)
    global_position = spawn_pos

func _process(delta):
    # rotate towards velocity, independent of movement
    rotation = lerp_angle(rotation, velocity.angle(), 0.3)

func _physics_process(delta):
    if target_player:
        var dir_to_player = global_position.direction_to(Master.player.global_position)
        velocity = dir_to_player * speed

    # move bullet
    global_position += velocity * delta

func _on_TimerTurn_timeout():
    target_player = true
by (112 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 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 webmaster@godotengine.org with your username.