您开始时将父母和孩子的数量相同(在本例中假设父母应该被控制,而孩子则不应该)。然后,您只需将孩子移动到父级的轴心点(在本例中为中心点),并在父级所面向的方向上添加一个额外的偏移量(偏移量当然是可选的)。
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()
我不能发布一个答案,但现在这里有一些提示:1.旋转孩子,移动它的支点,以其父的支点,当你做了父应用的精确转动。 2。然后使用父母方向矢量(如果没有方向矢量,可以从cos(角度),sin(角度))创建一个方向矢量,然后使用'direction * offset'移动孩子,其中* offset *是距离从父母的枢轴点到您想要孩子所在的位置。 –
@ted好吧,我已经想出了使用第一部分。这是方向矢量和移动我似乎有问题的孩子。在等待答案的同时,我会继续尝试解决它。谢谢 – ecool