如何使用 pymunk - python 让玩家粘在移动平台上?

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

我正在使用 pymunk 物理引擎构建一个平台游戏,并使用 pygame 来显示它。

我想知道如何才能让玩家粘在移动平台上?现在,如果我不通过移动玩家来跟随平台,玩家站在平台上时会保持在同一位置,然后当平台移开时会掉下来。

enter image description here

我的pygame/python版本:pygame 2.6.1(SDL 2.28.4,Python 3.12.3)

Pymunk 版本: 6.9.0

这是我正在使用的代码:

#Pymunk Platformer:
import pygame
import pymunk
import sys
import math

pygame.init()
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Platformer Game')
clock = pygame.time.Clock()

space = pymunk.Space()
space.gravity = (0, 900)  # Gravity pulls objects downwards


class Player(pygame.sprite.Sprite):
    def __init__(self, x, y, width=30, height=30):
        super().__init__()
        self.image = pygame.Surface((30, 30), pygame.SRCALPHA).convert_alpha()
        self.image.fill((255, 0, 0))  # Red square for player
        self.rect = self.image.get_rect(center=(x, y))

        # Pymunk physics body
        mass = 1
        self.width, self.height = width, height
        # inertia = pymunk.moment_for_box(mass, (width, height))
        # Setting the inertia to infinity makes it so that the rectangle does not rotate when colliding with other objects:
        inertia = float("inf")
        self.body = pymunk.Body(mass, inertia)
        self.body.position = x, y
        self.shape = pymunk.Poly.create_box(self.body, (width, height))
        self.shape.collision_type = 1  # Player collision type
        self.shape.friction = 1
        space.add(self.body, self.shape)
        self.on_ground = False
        self.angle = 0
        self.start_position = (x, y)

    def update(self):
        self.rect.center = self.body.position
        self.angle = math.degrees(self.body.angle)
        if self.body.position.y > 2000:
            self.body.position = self.start_position
            self.body.velocity = (0,0)

    def jump(self):
        if self.on_ground:
            self.body.velocity = (self.body.velocity.x, -300)  # Jump velocity
            self.on_ground = False


class Platform(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height):
        super().__init__()
        self.image = pygame.Surface((width, height))
        self.image.fill((0, 255, 0))  # Green rectangle for platforms
        self.rect = self.image.get_rect(topleft=(x, y))

        # Static body for platforms
        self.body = pymunk.Body(body_type=pymunk.Body.STATIC)
        self.body.position = x + width / 2, y + height / 2  # Center of the platform
        shape = pymunk.Poly.create_box(self.body, (width, height))
        shape.collision_type = 2  # Platform collision type
        shape.friction = 0.5
        space.add(self.body, shape)

    def update(self):
        pass  # Platforms don't need to update their position


class MovingPlatform(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height, range, speed):
        super().__init__()
        self.image = pygame.Surface((width, height))
        self.image.fill((0, 255, 0))  # Green rectangle for platforms
        self.rect = self.image.get_rect(topleft=(x, y))

        # Change to KINEMATIC instead of STATIC
        self.body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
        self.body.position = x+width/2, y+height/2  # Center of the platform
        self.shape = pymunk.Poly.create_box(self.body, (width, height))
        self.shape.collision_type = 2  # Platform collision type
        self.shape.friction = 1.5
        space.add(self.body, self.shape)

        self.range = range  # How far it moves
        self.speed = speed  # Speed of movement
        self.direction = 1  # 1 for moving right/up, -1 for left/down
        self.start_x, self.start_y = x, y

    def update(self):
        # Move the platform back and forth
        if self.body.position.x > self.start_x + self.range and self.direction == 1:
            self.direction = -1  # Reverse direction at edges
        if self.body.position.x < self.start_x and self.direction == -1:
            self.direction = 1  # Reverse direction at edges
        self.body.position = (self.body.position.x + self.direction * self.speed, self.body.position.y)# Set surface velocity to match platform movement
        self.shape.surface_velocity = (self.direction * self.speed, 0)

        self.rect.center = self.body.position


def player_on_ground(arbiter, space, data):
    for shape in arbiter.shapes:
        if shape == player.shape:
            player.on_ground = True
            return True
    return False

handler = space.add_collision_handler(1, 2)  # Player and Platform
handler.begin = player_on_ground

# Create player and platforms
player = Player(350, 200)
platforms = pygame.sprite.Group()
for _ in range(3):  # Create three platforms
    platforms.add(Platform(100 + _ * 200, HEIGHT - 200, 100, 20))
for i in range(2):
    platforms.add(Platform(20 + i * 300, HEIGHT - 300, 200, 20))
for i in range(2):
    ptfm = MovingPlatform(200 + i * 200, HEIGHT - 370, 40, 20, range=100, speed=1)
    platforms.add(ptfm)

all_sprites = pygame.sprite.Group(*platforms)
direction = "right"
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        player.body.velocity = (-150, player.body.velocity.y)  # Move left
    if keys[pygame.K_RIGHT]:
        player.body.velocity = (150, player.body.velocity.y)  # Move right
    if keys[pygame.K_SPACE]:
        player.jump()

    # Update physics
    space.step(1 / 60.0)

    # Update sprites
    all_sprites.update()
    player.update()

    # Draw
    screen.fill((0, 0, 0))
    all_sprites.draw(screen)
    rotated_image = pygame.transform.rotate(player.image, player.angle)
    width, height = rotated_image.get_size()
    half_width, half_height = int(width/2), int(height/2)
    x, y = player.rect.center
    screen.blit(rotated_image, [x - half_width, y - half_height])
    # print(player.body.position)

    pygame.display.flip()
    clock.tick(50)

pygame.quit()
sys.exit()
python pygame controls game-physics pymunk
1个回答
0
投票

您可以向 Player 附加一个布尔值,以确定 Player 是否“在移动平台上”。也许你可以称之为“onMovePlatform”。

您可以使用 PyMunk 的 CollisionHandler 类(https://www.pymunk.org/en/latest/pymunk.html#pymunk.CollisionHandler)来检测玩家是否位于 MovePlatform 对象上,或者在这种情况下,如果 Player 与 MovePlatform 对象“碰撞”。所以当Player与MovePlatform“碰撞”时,可以设置:“onMovePlatform = True

如果程序看到“onMovePlatform == True”,您可以这样做,以便每次 MovePlatform 的位置发生变化时,您都可以对 MovePlatform 使用相同的更改,并将其应用到 Player 位置。就像如果 MovePlatform 每帧向右移动 5 一样,您也可以为 Player 向右添加 5。这同样适用于其他方向,反之亦然。

然后,当您按空格键跳跃时,您可以自动设置 onMovePlatform = false,因为您可以假设由于您现在处于半空中,因此您不再与 MovePlatform 对象接触,并且由于布尔值现在设置为false,它不再将变换应用于玩家的位置。

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