Im making a 2d Space shooter game, and im asking if how can i shoot bullet automatically

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

please Help Space shooter automatic buller shoot

:bust_in_silhouette: Reply From: Tato64

Well, first of all you will need:

  • A separate scene for the bullet (A simple RigidBody2D, change the gravity scale to 0)
  • A timer (One-shot enabled) for the shot cooldown on the Spaceship’s
  • A Position2D on the Spaceship node, where the bullet will spawn.

You will preload the bullet on the Spaceship script like this:

var bullet = preload("res://PATH/TO/THE/BULLET/SCENE")

Then, start by checking if the key is being pressed and the cooldown ended, like this:

if Input.is_action_pressed("shoot") and $Timer.is_stopped():

And in the shoot() function:

func shoot():
       var bullet1 = bullet.instance()
       get_parent().add_child(bullet1)  #This is assuming the spaceship is a child of the scene root
       bullet1.global_position = $Position2D.global_position
       bullet1.linear_velocity.x = 300 #Change this number to make bullets slower or faster

And that should be it

:bust_in_silhouette: Reply From: magicalogic

Am assuming you want an enemy to automatically shoot a player when they come close to them.

All you need is to check whether the player is close to the enemy then shoot.

Add a variable in your enemy’s script to store the players position:

var player_position

This variable is to be updated in the _process method of the level where you are spawning the enemies as follows:

enemy.player_position = $Player.global_position

Use add this method in the enemy’s script to check whether the player is close enough:

func is_player_close():
    return get_global_position.distance_to(player_position) < 300

In the enemy’s script _process method, add:

if is_player_close():

All you need now is to add the shoot() method like @Tato64 has illustrated.