Matter.js calculating force needed

Viewed 3639

Im trying to apply a force to an object. To get it to move in the angle that my mouseposition is generating relative to the object.

I have the angle

 targetAngle = Matter.Vector.angle(myBody.pos, mouse.position);

Now I need to apply a force, to get the body to move along that angle. What do I put in the values below for the applyForce method?

  // applyForce(body, position, force)

  Body.applyForce(myBody, {
    x : ??, y : ??
  },{
    x:??, y: ?? // how do I derive this force??
  });

What do I put in the x and y values here to get the body to move along the angle between the mouse and the body.

2 Answers

You can rely on the Matter.Vector module and use it to substract, normalize and multiply positions vectors:

var force = 10;
var deltaVector = Matter.Vector.sub(mouse.position, myBody.position);
var normalizedDelta = Matter.Vector.normalise(deltaVector);
var forceVector = Matter.Vector.mult(normalizedDelta, force);
Body.applyForce(myBody, myBody.position, forceVector);
Related