We’re so close to a completed game at this point! Now it’s time to wire up our Player so it can shoot. We stubbed it earlier in Player.gd, time to revisit that code.
Change the _input() function in Player.gd, to look like:
Change the _input() function in Player.gd, to look like:
if(event.is_action("PLAYER_SHOOT")):
if(shotCooldown.time_left == 0):
var bullet = bulletObj.instance()
bullet.position = self.get_position()
bullet.position.y = bullet.position.y + 20
get_node("/root/GameSceneRoot").add_child(bullet)
shotCooldown.start()
This will spawn a bullet at the location of our Player and slightly down. After the bullet is spawned, we add it to the current scene. We also fire off a timer to prevent us from firing another bullet for a little while.
Load up the Player level in the 2D panel, and add a new Node of type Timer. Your Player object should now look like:
![]()
At this point, update your Player.gd script to match the following:
extends Node2D
# Called when the node enters the scene tree for the first time.
var speed = 150
var verticalMovement = 0
const MAX_VERTICAL_MOVEMENT = 200
var bulletObj = null
const RATE_OF_FIRE = 3.0
onready var shotCooldown = $Timer
func _ready():
bulletObj = load("res://Bullet/Bullet.tscn")
shotCooldown.wait_time = 1.0/RATE_OF_FIRE
shotCooldown.one_shot = true
func _process(delta):
move_local_x(speed*delta)
if(self.position.y > 1 && self.position.y <= get_viewport_rect().size.y):
move_local_y(verticalMovement*delta)
else:
if(self.position.y < 1):
move_local_y(10) #Bounce off top
verticalMovement = 0
if(self.position.y > get_viewport_rect().size.y):
move_local_y(-10) #Bounce off bottom
verticalMovement = 0
func stop():
speed = 0
func explode():
#Make sure we arent currently exploding!
if(!$AnimationPlayer.is_playing()):
$AnimationPlayer.play("Explode")
func dead():
get_node("/root/GameSceneRoot").PlayerDied()
func _input(event):
if(event.is_action("PLAYER_UP")):
if(verticalMovement >= -MAX_VERTICAL_MOVEMENT):
verticalMovement-=10
if(event.is_action("PLAYER_DOWN")):
if(verticalMovement <= MAX_VERTICAL_MOVEMENT):
verticalMovement+=10
if(event.is_action("PLAYER_SHOOT")):
if(shotCooldown.time_left == 0):
var bullet = bulletObj.instance()
bullet.position = self.get_position()
bullet.position.y = bullet.position.y + 20
get_node("/root/GameSceneRoot").add_child(bullet)
shotCooldown.start()
func _on_Area2D_area_entered(area):
#Layer 2 is another enemy
if(area.get_collision_layer_bit(2)):
explode()
We still need to implement the explosion logic in the above code.
