[英]Don't understand why object is bouncing off the wall / Pygame
So I was trying to do the DVD bounce on pygame and couldn't get it to hit the walls and bounce off but I eventually found someones elses method and used it but I can't figure out why it actually works , i don't understand why the DVD logo actually bounces off.所以我试图在 pygame 上做 DVD 弹跳,但无法让它撞到墙壁并弹开,但我最终找到了别人的方法并使用了它,但我不知道为什么它实际上有效,我不知道了解为什么 DVD 徽标实际上会反弹。 If someone could help that would be very much appreciated.如果有人可以提供帮助,将不胜感激。
import pygame
import os
os.chdir("C:\\Users\\user\\Documents\\Pythonscript\\DVD")
pygame.init()
def gameloop():
width = 600
height = 500
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('DVD')
black = (0,0,0)
dvd_logo = pygame.image.load("DVD Red.png")
rect = dvd_logo.get_rect()
clock = pygame.time.Clock()
game = False
move_speed = [2, 2]
while not game:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game= True
if rect.left < 0:
move_speed[0] = -move_speed[0]
dvd_logo = pygame.image.load("DVD Pink.png")
if rect.right > width:
move_speed[0] = -move_speed[0]
dvd_logo = pygame.image.load("DVD Blue.png")
if rect.top < 0:
move_speed[1] = -move_speed[1]
dvd_logo = pygame.image.load("DVD Yellow.png")
if rect.bottom > height:
move_speed[1] = -move_speed[1]
dvd_logo = pygame.image.load("DVD Red.png")
rect.left += move_speed[0]
rect.top += move_speed[1]
screen.fill(black)
screen.blit(dvd_logo, rect)
pygame.display.flip()
clock.tick(60)
gameloop()
pygame.quit()
quit()
So the rect
object represents the position and size of the dvd_logo
image.所以rect
对象代表了dvd_logo
图像的位置和大小。 In each frame, the code checks if the left
of rect
is less than zero (left edge of window), if right
is greater than width
(right edge of window), if top
is less than zero (top edge of window), or bottom
is greater than height
(bottom edge of window).在每一帧中,代码检查rect
的left
是否小于零(窗口的左边缘),如果right
大于width
(窗口的右边缘),如果top
小于零(窗口的上边缘),或bottom
大于height
(窗口的底部边缘)。 If the left
or right
are beyond the left or right edges, the move_speed[0]
(left/right speed) is negated, and the same is true for top
/ bottom
with move_speed[1]
.如果left
或right
超出左侧或右侧边缘,则move_speed[0]
(左/右速度)被否定,对于带有move_speed[1]
top
/ bottom
也是如此。
If your move_speed[0] is -2 (moving left) and rect.left
is less than zero, move_speed[0]
becomes 2
, so it'll move right instead of left.如果您的 move_speed[0] 为 -2(向左移动)并且rect.left
小于零,则move_speed[0]
变为2
,因此它将向右移动而不是向左移动。 Again, same concept for top/bottom and move_speed[1].同样,顶部/底部和 move_speed[1] 的概念相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.