我想出了如何在不同位置随机生成敌人的方法,但是我不知道如何使一些敌人随机发射子弹。
我创建了Bullet类和Enemy类。我使用attr_reader定位敌人并在新的Bullet方法中调用x和y位置,但是它无法找到敌人所在的位置。
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
我希望随机敌人会发射子弹。
答案 0 :(得分:1)
如评论中所讨论的,问题在于您拥有
@enemies.each do |enemy|
@enemy.draw
end
代替
@enemies.each do |enemy|
enemy.draw
end