如何在玩家移动位置的情况下,将我的雪碧旋转到玩家的位置上 Pygame

问题描述 投票:1回答:1

所以我有一个精灵,射出弹丸,弹丸射向玩家,我想知道我如何能使精灵旋转到玩家?视频 玩家的子弹会攻击玩家的任何位置,但我怎么能让他的子弹在他的位置上。炮烙?

我的大炮班

    shotsright = pygame.image.load("canss.png")
    class enemyshoot:
        def __init__(self,x,y,height,width,color):
            self.x = x
            self.y =y
            self.height = height
            self.width = width
            self.color = color
            self.shootsright = pygame.image.load("canss.png")
            self.shootsright = pygame.transform.scale(self.shootsright,(self.shootsright.get_width()-150,self.shootsright.get_height()-150))            
            self.rect = pygame.Rect(x,y,height,width)
            self.health = 10
            self.hitbox = (self.x + -20, self.y + 30, 31, 57)
        def draw(self):
            self.rect.topleft = (self.x,self.y)
            window.blit(self.shootsright,self.rect)
            self.hits = (self.x + 20, self.y, 28,60)
            pygame.draw.rect(window, (255,0,0), (self.hitbox[0], self.hitbox[1] - 60, 50, 10)) # NEW
            pygame.draw.rect(window, (0,255,0), (self.hitbox[0], self.hitbox[1] - 60, 50 - (5 * (10 - self.health)), 10))
            self.hitbox = (self.x + 100, self.y + 200, 81, 87)


    black = (0,0,0)
    enemyshoots1 = enemyshoot(1100,10,100,100,black)        
    enemyshooting = [enemyshoots1]


我的完整代码。脚本

python pygame
1个回答
3
投票

基本上,你可以旋转图像指向一些坐标很简单。 你创建一个大炮和玩家之间距离的向量。 然后将其转换为一个角度与 Vector.as_polar() 功能。 角度是用来旋转一个 原有 位图的副本到所需的角度。 图像旋转是相当耗费CPU的。

class enemyshoot:
    def __init__(self, x, y, height, width, color):
        [...]
        # Make a Reference Copy of the bitmap for later rotation
        self.original = pygame.image.load("canss.png")
        self.image    = self.original
        self.rect     = self.image.get_rect()
        self.position = pygame.math.Vector2( ( x, y ) )

    def lookAt( self, coordinate ):
        # Rotate image to point in the new direction
        delta_vector  = coordinate - self.position
        radius, angle = delta_vector.as_polar()
        self.image    = pygame.transform.rotozoom( self.original, -angle, 1 )
        # Re-set the bounding rectangle and position since 
        # the dimensions and centroid will have (probably) changed.
        current_pos      = self.rect.center
        self.rect        = self.image.get_rect()
        self.rect.center = current_pos

因此,我们的想法是,每次都取原始位图,并从该位图开始旋转。 如果你一直旋转同一个位图,轻微的差异就会复合,图像就会失去清晰度。

另外需要注意的是,我们是围绕位图的中心点旋转。 但是旋转会改变位图的尺寸,也会改变中心点。 所以这需要重新计算和保存。

你可能会发现,一旦旋转后的图像被旋转,缓存它们以节省CPU是很有用的。 也许可以将角度四舍五入到最接近的10度,然后看看它是否已经被旋转了。 这也可以让你预先旋转所有图像,并将它们存储在一个查找表中。

编辑: 调用 lookAt() 鼠标的位置。

rotating cannon

© www.soinside.com 2019 - 2024. All rights reserved.