python - 在 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()
输出
谢谢
解决方案
我想这是因为它们没有重力,因为它们都生活在各自独立的世界中……您可以尝试删除 Box 类中的 b2World() 并重新使用 main 的 self.world 吗?
推荐阅读
- django - NOT NULL 约束失败:accounts_sellerprofile.user_id
- c - C 内联函数
- flask - 错误请求烧瓶
- java - 为什么我不能在 Eclipse 2019-09 上安装 Gluon JavaFX?
- python - Pandas 数据帧的条件附加列表
- vim - 如果找到的行包含 ^M(必须是 unix 新行)字符,为什么 grep 不能显示它们?
- jquery - 悬停时更改文本颜色
- javascript - 为什么 XMLHttpRequest responseText 不存在?
- javascript - html 以包含另一个 html
- javascript - 如何从 index.d.ts 文件中手动导入类型,并告诉 VS Code 智能感知变量属于该类型?