[SOLVED] Collision component changes entity position

Hi everyone !

I am trying to render multiple templates, all with a collision component so that I can detect if the player has collided with the template.

In this project : PlayCanvas | HTML5 Game Engine I have set up a simple example for a use case of a box template being cloned, and rendered with a different position.

Here’s the code :

var Collision = pc.createScript('collision');

Collision.attributes.add('template', {
    title: 'Template',
    type: 'entity'
});

// initialize code called once per entity
Collision.prototype.initialize = async function() {
    const { template } = this;

   // Without collision
    for (let i = 0; i < 4; i++) {
        let clone = template.clone();
        clone.enabled = true;
        // We change the clone's location
        clone.localPosition = new pc.Vec3(clone.localPosition.x, clone.localPosition.y, clone.localPosition.z + (i * 1.1));
        this.app.root.addChild(clone);
    }
};

When no collision component is set up in “Template”, everything goes fine. The 4 cubes show up correctly, each with a different position. This is fine.

Now if in the code (or in the editor, that makes no difference), I add a collision component on the template (in this example, only the 3rd cube receives a collision component).

var Collision = pc.createScript('collision');

Collision.attributes.add('template', {
    title: 'Template',
    type: 'entity'
});


// initialize code called once per entity
Collision.prototype.initialize = async function() {
    const { template } = this;

   // With collision on the 3rd element of the array 
    for (let i = 0; i < 4; i++) {
        let clone = template.clone();
        clone.enabled = true;
        if (i === 2) clone.addComponent('collision', { type: 'box'} );
        clone.localPosition = new pc.Vec3(clone.localPosition.x, clone.localPosition.y, clone.localPosition.z + (i * 1.1));
        this.app.root.addChild(clone);
    }
};


This is what i get :

The 3rd cube hasn’t disappeared, it’s location has just been reset and is now rendered where the first cube is rendered as well.

Any idea you guys ?

Hi @F_Sabatie and welcome,

I am not fully sure why that happens, but I can see something wrong in your code there. Don’t read/set the localPosition directly (it’s an internal property), instead use the relevant get/setLocalPosition() methods.

If I change your code to this, then it works as expected:

   // With collision on the last element of the array 
    for (let i = 0; i < 4; i++) {
        let clone = template.clone();
        clone.enabled = true;
        if (i === 2) clone.addComponent('collision', { type: 'box'} );

        const localPosition = clone.getLocalPosition();
        clone.setLocalPosition(new pc.Vec3(localPosition.x, localPosition.y, localPosition.z + (i * 1.1)));
        this.app.root.addChild(clone);
    }
3 Likes

You are the freaking best my friend thank you so much !

1 Like