我想用pygame为我的ics课做一个总结来重现ballz。除了我不知道如何使球(这是一个图像)移动到用户点击的地方。你知道吗
这是pygame的,我尝试过更新位置,只是球在同一个位置忽进忽出。你知道吗
def level_2():
class Ball(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self) #construct the parent component
self.image = pygame.image.load("ball.png").convert_alpha()
self.image.set_colorkey(self.image.get_at( (0,0) ))
self.rect = self.image.get_rect() #loads the rect from the image
#set the position, direction, and speed of the ball
self.rect.left = 300
self.rect.top = 600
self.speed = 4
self.dir = 0
def update(self):
click = pygame.mouse.get_pressed()
#Handle the walls by changing direction(s)
if self.rect.left < 0 or self.rect.right >= screen.get_width():
self.dir_x *= -1
if self.rect.top < 0:
self.dir_y *= -1
####CHECK TO SEE IF BALL HITS THE BLOCK AND WILL BOUNCE####
if pygame.sprite.groupcollide(ball_group, block_group, False, True):
self.rect.move_ip(self.speed*self.dir_x, self.speed*self.dir_y)
if self.rect.bottom >= screen.get_height():
speed = 0
self.dir_y = 0
self.dir_x = 0
self.rect.left = 300
self.rect.top = 600
self.rect.move_ip(self.speed*self.dir_x, self.speed*self.dir_y)
#Move the ball to where the user clicked
if ev.type == MOUSEBUTTONDOWN:
(x, y) = pygame.mouse.get_pos()
#ASK MS WUN HOW TO DO #
if self.rect.left != x and self.rect.top != y:
#self.rect.move_ip(x, y)
self.rect.move_ip(self.speed*self.dir_x, self.speed*self.dir_y)
没有任何错误消息,唯一发生的事情是要么球会朝着设定的方向移动(如果用户单击右侧,球会向右移动,如果用户单击左侧,球仍会向右移动)。你知道吗
否则球就会在同一个地方忽进忽出
问题是,我认为(没有minimal, complete and verifiable example我无法正确判断)是对
Rect.move_ip()
的误解。此方法将Rect
转换为一个方向,而不是向它移动。由于您只能单击正坐标(负坐标在屏幕外),这意味着它将始终向下和向右移动。如果你想朝着某个方向前进,最简单的方法是这样的:然后用这个{}而不是球的位置来平移球。我认为此时您应该使用Pygame的Vector2类。那么等价物就是:
相关问题 更多 >
编程相关推荐