繁体   English   中英

如何使图像朝鼠标点击移动?

[英]How to make a image move towards mouse click?

我正在尝试使用pygame重新创建ballz,以便对我的ics类进行总结。 除了我不知道如何使球(这是一个图像)移动到用户点击的位置。

这是为了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)

没有任何错误消息,唯一发生的事情是球将按设定方向移动(如果用户点击右侧,球将向右移动,如果用户点击左侧,球仍将向右移动)。

或者球会在同一个地方闪烁

我认为这个问题(如果没有最小的,完整的,可验证的例子,我无法正确判断)是对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

然后通过这个翻译球movedir而非球的位置。 我想在这一点上你应该只使用Pygame的Vector2类。 那么等价物就是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM