如何使用 Ammo.js 中的 setUserPointer/getUserPointer

How to use setUserPointer/getUserPointer from Ammo.js

我想打印碰撞物体的名称。我做了一个很简单的例子。

我创建了一个对象来保存用户数据:

        const userData = { name: name };

我使用 setUserPointer 将此对象保存在主体中:

body.setUserPointer(userData);

我尝试使用 getUserPointer 获取此名称并打印它们。但我得到的是“未定义”而不是名称:

function detectCollison(): void
{
    const dispatcher = physicsWorld.getDispatcher();
    const numManifolds = dispatcher.getNumManifolds();

    for (let i = 0; i < numManifolds; i++)
    {
        const contactManifold = dispatcher.getManifoldByIndexInternal(i);
        const body0 = contactManifold.getBody0();
        const body1 = contactManifold.getBody1();

        const p0 = body0.getUserPointer();
        const p1 = body1.getUserPointer();

        console.log("first object: " + p0.name);
        console.log("second object: " + p1.name);
    }
}

已编辑

这是纯 TypeScript 版本。我试图将名称保留为主体 属性 但它也不起作用。它打印“未定义”而不是名称:

        (this.body as any).name = name;

        physicsWorld.addRigidBody(this.body);
function detectCollison(): void
{
    const dispatcher = physicsWorld.getDispatcher();
    const numManifolds = dispatcher.getNumManifolds();

    for (let i = 0; i < numManifolds; i++)
    {
        const contactManifold = dispatcher.getManifoldByIndexInternal(i);
        const body0 = contactManifold.getBody0();
        const body1 = contactManifold.getBody1();

        console.log("first object: " + (body0 as any).name);
        console.log("second object: " + (body1 as any).name);
    }
}

解决方案:

const userData = { name: name };
(this.body as any).userData = userData;
function detectCollison(): void
{
    const dispatcher = physicsWorld.getDispatcher();
    const numManifolds = dispatcher.getNumManifolds();

    for (let i = 0; i < numManifolds; i++)
    {
        const contactManifold = dispatcher.getManifoldByIndexInternal(i);
        const body0 = contactManifold.getBody0();
        const body1 = contactManifold.getBody1();

        const rb0 = (Ammo as any).castObject( contactManifold.getBody0(), Ammo.btRigidBody );
        const rb1 = (Ammo as any).castObject( contactManifold.getBody1(), Ammo.btRigidBody );

        console.log("first object:", rb0.userData);
        console.log("second object:", rb1.userData);
    }
}