I have figured out how to randomly spawn enemies in different locations, but I cant figure out to make some of the enemies randomly fire bullets.
I created a Bullet class and a Enemy class. I use attr_reader to locate the enemies and call the x and y locations in the new Bullet method, but it fails to find where the enemy is located.
require 'gosu'
require_relative 'player'
require_relative 'enemy'
require_relative 'bullet'
class Proto < Gosu::Window
WIDTH = 1000
HEIGHT = 800
ENEMY_FREQUENCY = 0.03
attr_reader :x, :y, :radius, :angle
def initialize
super(WIDTH,HEIGHT)
self.caption = "Proto"
@player = Player.new(self)
@enemies = []
@bullets = []
@framecounter = 0
end
def update
@framecounter += 1
@player.turn_left if button_down?(Gosu::KbLeft)
@player.turn_right if button_down?(Gosu::KbRight)
@player.accelerate if button_down?(Gosu::KbUp)
@player.backward if button_down?(Gosu::KbDown)
@player.move
if rand < ENEMY_FREQUENCY
@enemies.push Enemy.new(self)
end
@enemies.each do |enemy|
enemy.move
if @framecounter % 60 == 0 && @enemies[3]
@bullets.push Bullet.new(self, @enemy.x, @enemy.y, @enemy.angle)
end
end
@bullets.each do |bullet|
bullet.move
end
end
def draw
@player.draw
@enemies.each do |enemy|
enemy.draw
end
@bullets.each do |bullet|
bullet.draw
end
end
end
window = Proto.new
window.show
class Enemy
SPEED = 1
attr_reader :x, :y, :radius, :angle
def initialize(window)
@radius = 20
@x = rand(window.width - 2 * @radius) + @radius
@y = 0
@image = Gosu::Image.new('ima/tile000.png')
end
def move
@y += SPEED
end
def draw
@image.draw(@x - @radius, @y - @radius, 2)
end
end
require_relative 'enemy'
class Bullet
SPEED = 5
def initialize(window, x, y, angle)
@x = x
@y = y
@direction = angle
@image = Gosu::Image.new('ima/tile000.png')
@imaget = Gosu::Image.new('ima/tile000.png')
@radius = 3
@window = window
end
def move
@y += SPEED
end
def draw
@image.draw(@x - @radius, @y - @radius, 1)
@imaget.draw(@enemy.x - radius, @enemy.y - @radius, 1)
end
end
I expect random enemies to fire bullets.
As discussed in the comments, the issue was that you had
@enemies.each do |enemy|
@enemy.draw
end
instead of
@enemies.each do |enemy|
enemy.draw
end