首页 > 解决方案 > 在 pybox2d 物理模拟中,物体不会掉落

问题描述

我正在执行物理模拟,在该模拟中,我在鼠标单击位置创建物体,但物体不会因重力而下落。为什么它没有下降以及如何让它下降?我发布我的代码供您参考。

班级箱

import pygame
from Box2D import (b2EdgeShape, b2FixtureDef, b2PolygonShape, b2_dynamicBody,
                   b2_kinematicBody, b2_staticBody, b2World)

class Box:
    def __init__(self, x, y, PPM):
        self.x = x / PPM
        self.y = y / PPM
        self.w = .2
        self.h = .2

        self.world = b2World()
        self.attachment = self.world.CreateDynamicBody(
            position=(self.x, self.y),
            fixtures=b2FixtureDef(
                shape=b2PolygonShape(box=(self.w, self.h)), density=2.0, friction = 0.5),)
                
    def display(self, screen):
        for body in self.world.bodies:
            for fixture in body.fixtures:
                shape = fixture.shape
                vertices = [(body.transform * v) * 20 for v in shape.vertices]
                pygame.draw.polygon(screen, 'azure3', vertices)
                pygame.draw.polygon(screen, 'black', vertices,width=1)

主文件

import pygame
from box import Box
from Box2D import b2World

PPM = 20
TARGET_FPS = 60
TIME_STEP = 1.0 / TARGET_FPS

pygame.init()
screen = pygame.display.set_mode((600, 480))
pygame.display.set_caption("Physics")
clock = pygame.time.Clock()

# A list for all of our rectangles
boxes = []
world = b2World(gravity=(0, -10), doSleep=True)


close = False

while not close:
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            close = True
    
    screen.fill('white')

    click, _, _ = pygame.mouse.get_pressed()    
    if click == 1:
        x,y = pygame.mouse.get_pos()
        box = Box(x, y, PPM)
        boxes.append(box)

    for bo in boxes:
        bo.display(screen)

    world.Step(TIME_STEP, 10, 10)
    pygame.display.flip()
    clock.tick(TARGET_FPS)

pygame.quit()

输出

截屏

谢谢

标签: pythonpygamebox2d

解决方案


我想这是因为它们没有重力,因为它们都生活在各自独立的世界中……您可以尝试删除 Box 类中的 b2World() 并重新使用 main 的 self.world 吗?


推荐阅读