【问题标题】:sge-pygame rotating parent and child spritessge-pygame 旋转父子精灵
【发布时间】:2017-11-25 05:33:54
【问题描述】:

我一直在研究并试图弄清楚这一点。我正在尝试创建一个父/子附加系统,以便当父移动时,附加到它的子移动/旋转/缩放相同。我遇到的主要问题是轮换。

这是我目前为孩子们使用的代码:

def _rotate(self, origin, point, angle):
  ox, oy = origin
  px, py = point

  qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy)
  qy = oy + math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy)

  return qx, qy

_rotate 代码围绕我在寻找问题答案时找到的原点旋转一个 2D 点。我使用的点是每个框/精灵的中心。

旋转父级时,我使用 sge-pygame image_rotation 然后继续进行子级定位。之后我需要根据新位置和新角度来计算孩子的旋转来旋转孩子。

发生了什么的图片:

首字母

旋转10度

父母是大矩形,盒子是孩子。

我遇到的第二个问题是弄清楚孩子的旋转角度是什么,以使其与父母保持一致。我通过stackflow发现应该使用math.atan2,但是我似乎无法弄清楚如何使用它。

对此的任何帮助将不胜感激。

谢谢

【问题讨论】:

  • 我现在无法发布答案,但这里有一些提示: 1. 要旋转子级,请将其轴心点移动到其父级的轴心点,并像对父级所做的那样应用精确的旋转. 2. 然后使用父母的方向向量(如果你没有方向向量,你可以从 cos(angle), sin(angle) 创建一个)然后用direction * offset 移动孩子,其中 offset i> 是从父节点的轴心点到您希望子节点所在位置的距离。
  • @ted 好吧,我已经想通了使用第一部分。它是方向矢量并移动我似乎遇到问题的孩子。在等待您的答复的同时,我会继续努力解决。谢谢

标签: python rotation pygame 2d


【解决方案1】:

您首先将父项和子项轮换相同的数量(在此示例中,假定应控制父项,而子项不应控制)。然后你只需将孩子移动到父母的枢轴点(在这种情况下是它的中心),并在父母面对的方向上额外偏移(偏移当然是可选的)。

from math import cos, sin, radians
import pygame
pygame.init()

SIZE = WIDTH, HEIGHT = 720, 480
BACKGROUND_COLOR = pygame.Color('black')
FPS = 60

screen = pygame.display.set_mode(SIZE)
clock = pygame.time.Clock()


def update_child_rotation(parent, child, degrees, offset):
    # Rotate the parent and child with the same angle.
    parent.rotate(degrees)
    child.rotate(degrees)

    # Calculate the direction the parent is pointing. If you remember the unit circle then you'll
    # know that cos(angle) represent the x value and sin(angle) the y value. At angle = 0 the direction
    # is to the right (which is what your sprite should be pointing, otherwise you'll have to add an angle
    # offset), and it rotates counterclockwise. The minus in '-sin' is because pygame uses positive y as downwards.
    angle_in_radians = radians(parent.angle)
    direction = pygame.math.Vector2(cos(angle_in_radians), -sin(angle_in_radians))

    # Update the child's position to the parent's position but with an added offset in the direction the parent
    # is pointing.
    child.position = parent.position + direction * offset


class Entity(pygame.sprite.Sprite):

    def __init__(self, position, size):
        super().__init__()

        self.original_image = pygame.Surface(size)
        self.original_image.fill((255, 0, 0))
        self.original_image.set_colorkey(BACKGROUND_COLOR)

        self.image = self.original_image
        self.rect = self.image.get_rect(center=position)

        self.angle = 0
        self.position = pygame.math.Vector2(position)
        self.velocity = pygame.math.Vector2(0, 0)

    def rotate(self, degrees):
        self.angle = (self.angle + degrees) % 360
        self.image = pygame.transform.rotate(self.original_image, self.angle)
        self.rect = self.image.get_rect(center=self.position)

    def update(self, dt):
        self.position += self.velocity
        self.rect.center = self.position


def main():
    parent = Entity(position=(200, 200), size=(128, 32))
    child = Entity(position=(356, 200), size=(32, 32))
    all_sprites = pygame.sprite.Group(parent, child)

    running = True
    while running:

        dt = clock.tick(FPS) / 1000

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                    update_child_rotation(parent, child, 10, 156)
                elif event.key == pygame.K_e:
                    update_child_rotation(parent, child, -10, 156)
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT:
                    parent.velocity.x = 0
                elif event.key == pygame.K_DOWN or event.key == pygame.K_UP:
                    parent.velocity.y = 0

        all_sprites.update(dt)

        screen.fill(BACKGROUND_COLOR)
        all_sprites.draw(screen)
        pygame.display.update()


if __name__ == '__main__':
    main()

【讨论】:

    【解决方案2】:

    您可以在实例化期间将枢轴和所需的偏移量传递给子级(我在下面的示例中使用pygame.math.Vector2s)。如果父级移动,更新其所有子级(我将它们存储在一个列表中)并将父级的速度传递给它们,它们也可以用来更新它们的位置。

    旋转的工作原理类似,您只需将角度传递给孩子,然后旋转他们的偏移向量和图像,并将新矩形的中心设置为旧中心加上偏移。

    import sys
    import pygame as pg
    from pygame.math import Vector2
    
    
    class Player(pg.sprite.Sprite):
    
        def __init__(self, pos, *groups):
            super().__init__(groups)
            self.image = pg.Surface((90, 40), pg.SRCALPHA)
            self.image.fill(pg.Color('steelblue2'))
            self.orig_image = self.image
            self.rect = self.image.get_rect(center=pos)
            self.vel = Vector2(0, 0)
            self.pos = Vector2(pos)
            self.angle = 0
            # A list that holds all children instances.
            self.children = [Child(self.pos, Vector2(90, 30), *groups)]
    
        def update(self):
            self.pos += self.vel
            self.rect.center = self.pos
            for child in self.children:
                child.move(self.vel)
    
        def rotate(self, angle):
            self.angle += angle
            # Rotate the image and generate a new rect to keep it centered.
            self.image = pg.transform.rotate(self.orig_image, self.angle)
            self.rect = self.image.get_rect(center=self.rect.center)
            # Rotate the children.
            for child in self.children:
                child.rotate(angle)
    
    
    class Child(pg.sprite.Sprite):
    
        def __init__(self, pos, offset, *groups):
            super().__init__(groups)
            self.image = pg.Surface((50, 30), pg.SRCALPHA)
            self.image.fill(pg.Color('mediumaquamarine'))
            self.orig_image = self.image
            self.rect = self.image.get_rect(center=pos)
            self.pos = Vector2(pos)  # Parent center.
            # Offset from parent center.
            self.offset = Vector2(offset)
            self.angle = 0
    
        def move(self, vel):
            self.pos += vel
            self.rect.center = self.pos + self.offset
    
        def rotate(self, angle):
            # Rotate the offset vector (negative angle otherwise it would
            # rotate in the wrong direction).
            self.offset.rotate_ip(-angle)
            self.angle += angle
            # Rotate the image.
            self.image = pg.transform.rotate(self.orig_image, self.angle)
            # Add the new offset to the center.
            self.rect = self.image.get_rect(center=self.rect.center + self.offset)
    
    
    def main():
        screen = pg.display.set_mode((640, 480))
        clock = pg.time.Clock()
        sprite_group = pg.sprite.Group()
        player = Player((100, 250), sprite_group)
    
        done = False
    
        while not done:
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    done = True
                elif event.type == pg.KEYDOWN:
                    if event.key == pg.K_d:
                        player.vel.x = 5
                    elif event.key == pg.K_r:
                        player.rotate(15)
                    elif event.key == pg.K_c:
                        player.children.append(Child(
                            player.pos, Vector2(-90, -30), sprite_group))
                elif event.type == pg.KEYUP:
                    if event.key == pg.K_d:
                        player.vel.x = 0
    
            sprite_group.update()
            screen.fill((30, 30, 30))
            sprite_group.draw(screen)
    
            pg.display.flip()
            clock.tick(30)
    
    
    if __name__ == '__main__':
        pg.init()
        main()
        pg.quit()
        sys.exit()
    

    按“d”向右移动,按“r”旋转,按“c”添加更多子项。

    【讨论】:

    • 我对 SGE 不熟悉。它是否允许您使用 pygame 精灵、精灵组和矢量?如果没有,您可能可以根据您的要求调整代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    • 2013-03-13
    相关资源
    最近更新 更多