帮忙解决设计问题

发布于 2024-11-18 14:00:09 字数 418 浏览 1 评论 0原文

这是我的问题。

我正在使用一个名为 Box2D 的物理库。我可以连接一个监听器,它会在两个灯具发生碰撞时告诉我。

本质上,Box2D 的工作方式是创建 b2Bodies。因此,我只知道碰撞的fixture属于哪个b2Body。在我的游戏中,我有一个实体,并且从中我有一个 PhicsEntity。一个PhysicsEntity持有一个指向b2Body的指针。它还有一个来自 Entity 的 sendMessage 方法。问题是,如何从 b2Body 向PhysicsEntity 发送碰撞消息。我想做的是将 b2Body 的 userData void* 设置为其对应的PhysicsEntity。不过,必须强制转换 void* 来执行此操作似乎非常错误。

有没有更好的方法可以让我快速了解与 b2Body 关联的物理实体,而无需进行强制转换或查找?

谢谢

Here is my problem.

I'm using a physics library called Box2D. I'm able to hook up a listener that will tell me when 2 fixtures collide.

Essentially the way Box2D works is by creating b2Bodies. Therefore, I only know which b2Body the fixture that collided belongs to. In my game, I have an Entity, and from that I have a PhisicsEntity. A PhysicsEntity holds a pointer to a b2Body. It also has a sendMessage method that comes from Entity. The problem is, from the b2Body, how do I send the PhysicsEntity a collision message. What I thought of doing was to set the userData void* of the b2Body to its corresponding PhysicsEntity. It seems very wrong to have to cast a void* to do this though.

Is there a better way that I could very quickly know the Physics Entity associated with the b2Body without casting or lookup?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

人心善变 2024-11-25 14:00:09

这正是 userData 字段之类的字段的用途 - 引用与库对象相关的应用程序数据。这是 void * 的完全正确的使用。

如果您询问有关 C 的问题,我会说您也不应该使用任何强制转换,因为可以在不进行任何强制转换的情况下完成与 void * 的转换,并且需要使用强制转换是一个标志一个可能的问题,但如果我没记错的话,C++ 需要这些转换(我使用 C++ 的程度不足以确定)。

This is exactly the purpose that fields like that userData field are for — to refer to your application's data related to the library's object. This is an entirely appropriate use of void *.

If you were asking about C, I would say that you should also not have to use any casts, as converting to and from void * can be done without any casts and needing to use a cast is a sign of a possible problem, but if I recall correctly C++ requires those casts (I do not use C++ enough to be sure).

薄荷梦 2024-11-25 14:00:09

这实际上正是 userData 指针的用途。这是一个相当标准的范例 - 看看 pthread_create 或 CreateThread 等函数作为另一个例子。

如果您遇到一个不允许您使用 void * 的库(或者不安全 - 例如将其存储为 int 本地),那么您可以使用 std::map 来解析该类型。但这会更慢并且开销更大。

That's actually exactly what the userData pointer is meant for. It's a fairly standard paradigm - look at functions such as pthread_create or CreateThread for another example.

If you encounter a library that doesn't allow you to use a void * (or not safely - such as storing it locally as an int) then you can use an std::map to resolve the type. That's slower and with much more overhead though.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文