我正在写一个乒乓球游戏,一切正常——得分检测、从墙上弹起、桨的移动等。但是,乒乓球不会从桨上反弹,而是直接穿过它们。 (郑重声明,我在 MicroPython 上使用 pimoroni-pico 库执行此操作,所以这就是
button_up.is_pressed
的意义所在)。
x = 160
y = 120
p1point = 0
p2point = 0
x_speed = random.choice([-3.0,3.0])
y_speed = random.choice([-3.0,3.0])
aipad = 110
plpad = 110
width = 320
height = 240
while True:
# Controls bouncing off walls
if (x >= width) or (x <= 0):
x_speed *= -1
if (y >= height) or (y <= 0):
y_speed *= -1
# Supposed to control bouncing off paddles, and choose a slightly random rebound
if (aipad > y > aipad+20 and x < 5) or (plpad > y > plpad+20 and x > 315):
x_speed += random.random()
y_speed += random.random()
x_speed *= -1
if x_speed > 5 or y_speed > 5:
x_speed = 3
y_speed = 3
print("flip")
# Adds score for respective player
if x < 0:
x_speed = 3
y_speed = 3
x = 160
y = 120
p2point += 1
sleep(1)
if x > 320:
x_speed = -3
y_speed = -3
x = 160
y = 120
p1point += 1
sleep(1)
# AI player's ai
if y < aipad:
aipad = aipad - 4
if y > aipad:
aipad = aipad + 4
# Human player's controls
if button_up.is_pressed
plpad = plpad - 3
if button_down.is_pressed:
plpad = plpad + 3
# Stops the paddles from going too far off screen
if plpad > 220:
plpad = 220
if aipad > 220:
aipad = 220
if plpad < 0:
plpad = 0
if aipad < 0:
aipad = 0
# Adds _speed to the respective positional variable, rounding down x_speed
x += int(x_speed)
y += int(y_speed)
# ... render play field ...
我试过以不同的方式重写回弹代码,将不等式符号从
>
更改为>=
,更改数字,什么都没有。我还尝试将速度降低到每刻度 1 个像素(它可能已经越过碰撞区),但这没有用。有一次它开始随机振动,远离边缘,但我不知道如何重现。这可能是一个愚蠢的错误,但我找不到它。
变量:
*垫子的原点距离屏幕 (X) 5 个像素,在它的位置变量 (Y),它穿过 1 个像素朝向屏幕的最近边缘(2 像素宽)并向下 20(20 像素高) .
您想确定
y
是否在aipad
(或plpad
)和aipad+20
之间。如果你写:
1 > 2 > 3
你可以明显看出
1>2
是假的,所以这不是你想要的。相反,您需要:
aipad < y < aipad+20