python - 如何使用 PyBox2d 检测碰撞并使用该信息
问题描述
我正在尝试通过复制此示例来过滤我的 Box2D 世界中发生的冲突:https ://github.com/pybox2d/pybox2d/blob/master/examples/collision_filtering.py
我的世界中有四个类,汽车、车轮、建筑和行人,我想过滤哪个实例与哪个实例发生碰撞,其中一个可能的输出是(伪代码)
if contact.FixtureA.isinstance(Pedestrian) and contact.FixtureB.isinstance(Car):
print("You have caused a traffic accident")
我有这组类别
CAR_CATEGORY = 2
PEDESTRIAN_CATEGORY = 4
BUILDING_CATEGORY = 8
box2world = world(gravity =(0.0, 0.0), doSleep =True)
我也试过这个:但它不起作用(它什么都不做)
class myContactListener(b2ContactListener):
def __init__(self):
b2ContactListener.__init__(self)
def BeginContact(self, contact):
fixture_a = contact.fixtureA
fixture_b = contact.fixtureB
body_a, body_b = fixture_a.body, fixture_b.body
ud_a, ud_b = body_a.userData, body_b.userData
pedestrian = None
car = None
for ud in (body_a, body_b):
if isinstance(ud, Pedestrian):
pedestrian = ud
elif isinstance(ud, Car):
car = ud
if car is not None and pedestrian is not None:
if began:
print("It does stuff")
else:
print("It does something")
def EndContact(self, contact):
pass
def PreSolve(self, contact, oldManifold):
pass
def PostSolve(self, contact, impulse):
pass
box2world = world(contactListener=myContactListener(),gravity =(0.0, 0.0), doSleep =True)
我在给定的类中应用它(为简单起见,仅显示类 Pedestrian):
class Pedestrian():
def __init__(self,box2world, ped_velocity =25, position =None,):
if position == None:
position = [5,5]
self.ped_velocity = ped_velocity
self.position = position
self.box2world = box2world
self.nearest_building = 0
self.body = self.box2world.CreateDynamicBody(position = position,
angle = 0.0,
fixtures = b2FixtureDef(
shape = b2CircleShape(radius = 1),
density = 2,
friction = 0.3,
filter = b2Filter(
categoryBits=PEDESTRIAN_CATEGORY,
maskBits=BUILDING_CATEGORY + CAR_CATEGORY,
groupIndex=0,
)))
self.current_position = [self.body.position]
self.body.userData = {'obj': self}
然后我绘制身体并使用 pygame 运行世界
但是我对如何继续感到困惑,我怎么能使用来自碰撞过滤器的信息来例如从上面打印关于事故的句子?
非常感谢编辑:我找到了一个链接,它可以解决我想要做的事情,但它是用 C++ 编写的,我不明白它 http://www.iforce2d.net/b2dtut/collision-callbacks
解决方案
嘿,我刚刚在 stackexchange 上回答了你的问题 :-)
对于碰撞很容易:
local filterData = {
categoryBits = player,
maskBits = wall + nme + platform,
groupIndex = 0
}
fixture:setFilterData(filterData)
player , wall , nme , ... 是整数变量(必须是 2 的幂):
player = 1
wall = 2
nme = 4
... = 16, 32, 64, 128, 256, ...
categoryBits = 您要测试碰撞的主要对象
maskBits = 您添加(使用 +)主要对象可以碰撞的所有数字。
最好将数字存储为变量,否则看起来像:
local filterData = {
categoryBits = 1,
maskBits = 2 + 4 + 8 + 16 ...,
groupIndex = 0
}
fixture:setFilterData(filterData)
:-)
推荐阅读
- java - 从 JSON 字段中检索值
- python - 将更大的字典项转换为 HTML 表格格式:性能改进
- java - Spring boot - 添加自定义 MongoDB 转换器
- c# - 结合 BinaryExpression 和 Expression
> 在 C# 中 - javascript - 向 Web API 发送参数时参数值设置为 0
- c++ - 为什么 gcc 仅针对统一初始化发出关于缩小转换的警告?
- hive - 在 hive 中不使用窗口函数实现 Dense_rank 函数
- python - 将变量作为函数传递给对象时出错。在 Python 3.7.0pyt 中
- java - Spring Boot解析yaml配置
- python - 如何访问报纸3k中的缓存文章