问题描述
我一直在尝试让我的乒乓球比赛中的球弹回桨,但它只是卡住并向上拖动,我不知道如何修复它。 这是我的代码:
require 'ruby2d'
set background: 'black'
#set resizable: 'true'
class Racket
attr_writer :direction
def initialize(side,speed)
@movement = speed
@direction = nil
@y = 200
if side == :left
@x = 40
else
@x = 580
end
end
def move
if @direction == :up
@y = [@y - @movement,0].max
elsif @direction == :down
@y = [@y + @movement,330].min
end
end
def draw
@shape = Rectangle.new(x: @x,y: @y,width: 25,height: 150,color: 'white')
end
def ball_contact?(ball)
ball.shape && [[ball.shape.x1,ball.shape.y1],[ball.shape.x2,ball.shape.y2],[ball.shape.x3,ball.shape.y3],[ball.shape.x4,ball.shape.y4]].any? do |coordinates|
@shape.contains?(coordinates[0],coordinates[1])
end
end
end
class Ball
HEIGHT = 25
attr_reader :shape
def initialize
@x = 320
@y = 400
@x_speed = -1
@y_speed = 1
end
def move
if hit_bottom_edge?
@y_speed = -@y_speed
end
@x = @x + @x_speed
@y = @y + @y_speed
end
def draw
@shape = Square.new(x: @x,size: HEIGHT,color: 'red')
end
还有这里的某个地方,因为这是球从桨上弹开并击中玩家 2 的功能:
def bounce
@x_speed = -@x_speed
end
def hit_bottom_edge?
@y + HEIGHT >= Window.height
end
end
player_1 = Racket.new(:left,3)
player_2 = Racket.new(:right,3)
ball = Ball.new
update do
clear
if player_1.ball_contact?(ball)
ball.bounce
elsif player_2.ball_contact?(ball)
ball.bounce
end
player_1.move
player_2.move
player_1.draw
player_2.draw
ball.draw
ball.move
end
on :key_down do |event|
if event.key == 'w'
player_1.direction = :up
elsif event.key == 's'
player_1.direction = :down
end
if event.key == 'up'
player_2.direction = :up
elsif event.key == 'down'
player_2.direction = :down
end
end
on :key_up do |event|
player_1.direction = nil
player_2.direction = nil
end
show
它仍在进行中,因为我还没有创建一个让球从顶部边缘反弹的函数。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)