Here’s a quick script I whipped up to implement a point-to-point constraint in PlayCanvas:
var PointToPointConstraint = pc.createScript('pointToPointConstraint');
PointToPointConstraint.attributes.add('pivotA', {
description: 'Position of the constraint in the local space of this entity',
type: 'vec3',
default: [0, 0, 0]
});
PointToPointConstraint.attributes.add('entityB', {
description: 'Optional second entity',
type: 'entity'
});
PointToPointConstraint.attributes.add('pivotB', {
description: 'Position of the constraint in the local space of entity B (if specified)',
type: 'vec3',
default: [0, 0, 0]
});
PointToPointConstraint.attributes.add('debugRender', {
description: 'Enable to render a representation of the constraint',
type: 'boolean',
default: false
});
PointToPointConstraint.attributes.add('debugColor', {
description: 'The color of the debug rendering of the constraint',
type: 'rgb',
default: [1, 0, 0]
});
// initialize code called once per entity
PointToPointConstraint.prototype.initialize = function() {
this.createConstraint();
this.on('attr', function(name, value, prev) {
// If any constraint properties change, recreate the constraint
if (name === 'pivotA' || name === 'entityB' || name === 'pivotB') {
this.createConstraint();
}
});
this.on('enable', function () {
this.createConstraint();
});
this.on('disable', function () {
this.destroyConstraint();
});
this.on('destroy', function () {
this.destroyConstraint();
});
};
PointToPointConstraint.prototype.createConstraint = function() {
if (this.constraint) {
this.destroyConstraint();
}
var bodyA = this.entity.rigidbody.body;
var pivotA = new Ammo.btVector3(this.pivotA.x, this.pivotA.y, this.pivotA.z);
if (this.entityB && this.entityB.rigidbody) {
var bodyB = this.entityB.rigidbody.body;
var pivotB = new Ammo.btVector3(this.pivotB.x, this.pivotB.y, this.pivotB.z);
this.constraint = new Ammo.btPoint2PointConstraint(bodyA, bodyB, pivotA, pivotB);
} else {
this.constraint = new Ammo.btPoint2PointConstraint(bodyA, pivotA);
}
var dynamicsWorld = this.app.systems.rigidbody.dynamicsWorld;
dynamicsWorld.addConstraint(this.constraint);
this.entity.rigidbody.activate();
if (this.entityB) {
this.entityB.rigidbody.activate();
}
};
PointToPointConstraint.prototype.destroyConstraint = function() {
var dynamicsWorld = this.app.systems.rigidbody.dynamicsWorld;
dynamicsWorld.removeConstraint(this.constraint);
Ammo.destroy(this.constraint);
};
// update code called every frame
PointToPointConstraint.prototype.update = function(dt) {
if (this.debugRender) {
var tempVecA = new pc.Vec3();
this.entity.getWorldTransform().transformPoint(this.pivotA, tempVecA);
this.app.renderLine(this.entity.getPosition(), tempVecA, this.debugColor);
if (this.entityB) {
this.app.renderLine(this.entityB.getPosition(), tempVecA, this.debugColor);
}
}
};
Other constraint types can be created in a similar fashion.
Project: https://playcanvas.com/project/618829
What do you think?