如何使图像朝着鼠标点击的方向移动?

2024-03-29 00:03:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用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)

没有任何错误消息,唯一发生的事情是要么球会朝着设定的方向移动(如果用户单击右侧,球会向右移动,如果用户单击左侧,球仍会向右移动)。你知道吗

否则球就会在同一个地方忽进忽出


Tags: the用户rectimageselfipgetmove
1条回答
网友
1楼 · 发布于 2024-03-29 00:03:21

问题是,我认为(没有minimal, complete and verifiable example我无法正确判断)是对Rect.move_ip()的误解。此方法将Rect转换为一个方向,而不是向它移动。由于您只能单击正坐标(负坐标在屏幕外),这意味着它将始终向下和向右移动。如果你想朝着某个方向前进,最简单的方法是这样的:

target_x = 100
target_y = 300
ball_x = 600
ball_y = 200
movedir_x = target_x - ball_x
movedir_y = target_y - ball_y
# Now adjust so that the speed is unaffected by distance to target
length = (movedir_x ** 2 + movedir_y ** 2) ** 0.5
movedir_x *= speed / length
movedir_y *= speed / length

然后用这个{}而不是球的位置来平移球。我认为此时您应该使用Pygame的Vector2类。那么等价物就是:

target = pygame.math.Vector2(100, 300)
ball = pygame.math.Vector2(600, 200)
movedir = (target - ball).normalize() * speed

相关问题 更多 >