我已经想出了如何在不同的位置随机生成敌人,但我无法弄清楚让一些敌人随机发射子弹。
我创建了一个 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
我希望随机的敌人发射子弹。