本文介绍了在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)
main.py
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?
这篇关于在pybox2d物理模拟中,物体不会坠落的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!