matter-js icon indicating copy to clipboard operation
matter-js copied to clipboard

Raycasting as a part of different objects

Open DannyXY opened this issue 3 years ago • 3 comments

I'm trying to work on a piece of code where there are multiple bodies in the scene and they all have raycasts that rotate when the body rotates, so this way i can attach a detection reaction to them I already tried using sensors alongside the rays ad it didn't give me what i want

DannyXY avatar Nov 25 '22 22:11 DannyXY

Could you share an example of the issue and explain further?

liabru avatar Nov 26 '22 10:11 liabru

I created a rectangle sensor to server as a ray

sensorA = Bodies.rectangle(
  partA.vertices[0].x - size / 2 - 200,
  partA.vertices[0].y + size / (5 * 2),
  600,
  1,
  {
    render: {
      fillStyle: "#f00",
    },
    isSensor: true,
    label: "raycastSensor1",
  }
);

Then i used the Query.ray to track the positions of the sensor and return details on the collisions

var collisions = []
Events.on(engine, "afterUpdate", function () {
   //The sensor was attached to the bodies as a complex body/composite so i had to state the bodies i waned to track so i does not track the sensor object too
   var bodies = [partA, partB, partI, partJ, partM, partN, partO, partP],
    startPoint = sensorA.vertices[0],
    endPoint = sensorA.vertices[3];

  collisions = Query.ray(bodies, startPoint, endPoint);

  console.log(collisions);
});

Events.on(render, "afterRender", function () {
  for (var i = 0; i < collisions.length; i++) {
    var collision = collisions[i];
    context.rect(
      collision.bodyA.position.x - 4.5,
      collision.bodyA.position.y - 4.5,
      8,
      8
    );
  }

for some reason all it console logs on collision is still the raycastSensor1 as the bodyA and bodyB, is there any other way to go about it This is my first week using matterJS so my approach might be wrong Please help

DannyXY avatar Nov 26 '22 12:11 DannyXY

I think in principle that seems like it might work, though as it stands I think Query.ray intentionally does not return individual parts (only the parent).

So you could try make your own copy of the Query.ray function and remove this line which might do the trick?

liabru avatar Mar 15 '23 23:03 liabru