0

我一直试图在我的乒乓球比赛中让球弹起 Paddle,但它只是卡住并向上拖动,我不知道如何解决它。这是我的代码:

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, y: @y, 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

这仍然是一项正在进行的工作,因为我还没有创建球从上边缘反弹的功能。

4

0 回答 0