Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
429 views
Welcome To Ask or Share your Answers For Others

1 Answer

To apply a force to move your object in that direction you need to take the sine and cosine of the angle in radians. You'll want to just pass the object's position as the first vector to not apply torque (rotation).

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

Body.applyForce(myBody, myBody.position, {
  x: cos(targetAngle) * force, 
  y: sin(targetAngle) * force
});

Also if you need it, the docs on applyForce() are here.

(I understand this question is old, I'm more or less doing this for anyone who stumbles across it)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...