pygame 中的定位和物理问题。角色碰撞后立即向相反方向跳跃

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

我的角色在与瓷砖碰撞后会直接跳跃。它的水平和垂直定位都有缺陷。请帮忙

enter image description here

实体.py:

import pygame

class PhysicsEntity:
    def __init__(self, game, entity_type, pos, size):
        self.game = game
        self.entity_type = entity_type
        self.pos = list(pos) # Convert to list
        self.size = size
        self.velocity = [0, 0]
        self.collisions = {'up': False, 'down': False, 'left': False, 'right': False}
    
    def rect(self):
        return pygame.Rect(self.pos[0], self.pos[1], self.size[0], self.size[1])
    
    def update(self, tilemap, movement=(0, 0)):
        self.collisions = {'up': False, 'down': False, 'left': False, 'right': False}
        
        frame_movement = (movement[0] + self.velocity[0], movement[1] + self.velocity[1])
        
        self.pos[0] += frame_movement[0] # x axis
        entity_rect = self.rect()
        for rect in tilemap.physics_rects_around(self.pos):
            if entity_rect.colliderect(rect):
                if frame_movement[0] > 0:
                    entity_rect.right = rect.left
                    self.collisions['right'] = True
                if frame_movement[0] < 0:
                    entity_rect.left = rect.right
                    self.collisions['left'] = True
                self.pos[0] = entity_rect.x # <--- jumping bug
        
        self.pos[1] += frame_movement[1] # y axis
        entity_rect = self.rect()
        for rect in tilemap.physics_rects_around(self.pos):
            if entity_rect.colliderect(rect):
                if frame_movement[1] > 0:
                    entity_rect.bottom = rect.top
                    self.collisions['down'] = True
                if frame_movement[1] < 0:
                    entity_rect.top = rect.bottom
                    self.collisions['up'] = True
                    
                self.pos[1] = entity_rect.y # <--- jumping bug
        
        self.velocity[1] = min(5, self.velocity[1] + 0.1) # physics
        
        if self.collisions['down'] or self.collisions['up']:
            self.velocity[1] = 0
        
    def render(self, surf):
        surf.blit(self.game.assets['player'], self.pos)

我尝试让物理在pygame中发挥作用,并期望顺利落地

python pygame position game-physics physics
1个回答
0
投票

解决了问题,问题是这样的 self.player =PhysicsEntity(self, "玩家", (50, 50), (16, 16))

在最后一个参数中我输入了一些大数字

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