0 votes

please Help Space shooter automatic buller shoot

in Engine by (12 points)

2 Answers

0 votes

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
    node.
  • 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():
   shoot()

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

by (213 points)
0 votes

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():
    shoot()

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

by (1,051 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.