Hi,
It’s really great developing on play canvas. I now have HTC vive controllers looking like guns firing with muzzle flashes and hitting boxes (thanks to everyone for the tips). What I would love to know now is how you make the boxes react realistically. From the documentation it looks like you can identify where the raycast from the gun strikes the box and I am guessing that I can use that to figure out what linear and angular impulses i need to apply to the box when it is struck but I just don’t know how at the moment? and do I need to apply both linear and angular impulses or does the linear spin the box if it is coming in at an angle?
I will probably mess around with it for a bit but if anyone has an example for me to look at it would really help.
So yes, to make the boxes react correctly to the strike of a bullet, you would use an impulse rather than a force. An impulse is a force applied in an instant (used for making a character jump, say) whereas a force is applied over time (to push a body over a surface, say).
So you know the position and direction of your gun. That’s the ray that you would perform a raycast with. The raycast result gives you the point of intersection in world space. So you would apply an impulse to the hit body that has the same direction as the ray. The only thing you need to do is also supply the relative point to apply the impulse in the local coordinate space of the hit entity. To do this, transform the world space intersection point supplied by pc.RayCastResult into local space of the entity.
I believe you would have to transform that point by the inverse world transformation matrix of the entity. So something like:
var from = gunEntity.getPosition();
var to = from.clone();
to.add(gunEntity.forward.clone().scale(1000));
app.systems.rigidbody.raycastFirst(from, to, function (result) {
var hitEntity = result.entity;
var localOffset = new pc.Vec3();
var mat = hitEntity.getWorldTransform().clone();
mat.invert();
mat.transformPoint(result.point, localOffset);
hitEntity.applyImpulse(rayDir, localOffset);
});