Adding mesh collision through code

I’ve been trying to add collision to my models in a previous topic, but I’m creating a new one as this is more specific.

So I am trying to add mesh collision components to my models through code using this snipped:

entity.addComponent('collision', {
    type: "mesh",
    model: this.entity.model.model,
    asset: this.entity.model.asset

This works on a model (without collision component) placed in the editor, but not when I have loaded the model from web:, "model", function (err, asset) {
    if(err){ console.log(err); return;}

    var entity = new pc.Entity();
    entity.model.model = asset.resources[0];

    var collider = entity.addComponent('collision', {
        type: 'mesh',
        model: entity.model.model,
        asset: entity.model.asset
    console.log("added col", collider);;

Logging this collision component shows that both the asset and model properties are null.

test.js prints a collision component added in editor
test2.js prints a collision component added through code
raycast.js adds cube from web and adds collision which doesn’t work

Hi @ivodidutch,

You should add the mesh collider like this:

        var collider = entity.addComponent('collision', {
            type: 'mesh',
            asset: asset

Though this will still not work for your model in question. As you stated on the other post (do try avoiding opening a new post for the same subject, there were useful remarks there), there is an error coming up:

The mesh parser that creates the physics shape for Ammo failed to execute because this model is not indexed (the OBJ is missing an indices array).

Try loading any other indexed OBJ and I think it will work.

It might have to do with the general obj parser. I will switch to .glb using the new development build for now, seems to work a bit easier. Would be really nice to have a .obj parser integrated in the engine :stuck_out_tongue:

1 Like