0 votes

I'm new to Godot and I'm trying to code fire bullets, when I use area2d type, there's an error in the 'apply impulse' section like "invalid call. Nonexistent function 'apply_impulse' in base 'Area2D(Bullet.gd)'. What do I have to do?
here's my code :
(Bullet.gd)

extends Area2D

export (PackedScene) var bullet

func _on_KillTimer_timeout():
    pass # Replace with function body.

func _on_Bullet_body_entered(body):
    if !body.is_in_group("player"):
        queue_free()

then my code in gun.gd :

extends Sprite

    export var bullet_speed = 1000
    export var fire_rate = 0.2

    var bullet = preload("res://Characters/Player/Bullet.tscn")
    var can_fire = true

    func _process(delta):
        var mouse_direction: Vector2 = (get_global_mouse_position() - global_position).normalized()
        look_at(get_global_mouse_position())

        if Input.is_action_pressed("fire") and can_fire:
            var bullet_instance = bullet.instance()
            bullet_instance.position = $BulletPoint.get_global_position()
            get_parent().screen_shaker._shake(0.2, 2)
            bullet_instance.rotation_degrees = rotation_degrees + rand_range(0.1, 0.1)
            bullet_instance.apply_impulse(Vector2(), Vector2(bullet_speed, 0).rotated(rotation))
            get_tree().get_root().add_child(bullet_instance)
            can_fire = false
            yield(get_tree().create_timer(fire_rate),"timeout")
            can_fire = true
Godot version v3.4.4
in Engine by (12 points)

1 Answer

0 votes

apply_impulse() is a method that belongs to the RigidBody2D class: https://docs.godotengine.org/en/stable/classes/class_rigidbody2d.html

So no, you can't use it with an Area2D. It seems that you have copied code that someone wrote to implement a RigidBody2D bullet, but you're trying to run it on the wrong type of node.

There's nothing wrong with using an Area2D for a bullet - indeed, it's probably the most common node used for this. But areas aren't moved/controlled by the physics engine, so you have to change their position in code rather than applying forces or impulses like you'd do with a rigid body.

by (21,714 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.