TLDR; How do I make a body draggable only in the bottom half of the screen and release it if user tries to go beyond that specified area?
I'm making a simple game using p5.js for rendering and Matter JS as the physics Engine. The game involves tossing a ball towards targets to gain points. But I'm not sure how to prevent the player from simply dragging the ball all over the targets. I'd like to limit the area of the screen in which the user can drag the ball.
I try to achieve it by explicitly setting the position of the body, but that seems to break the physics of the body completely and now it doesn't collide with anything anymore.
Demo With Error: https://toss-game-8d371.web.app/
RELEVANT CODE:
//Inside the p5 setup() function
Matter.Events.on(engine, "afterUpdate", () => {
if(p.mouseIsPressed && p.mouseY < 600 && ball.body.position.y < 600) {
console.log("out");
ball.body.position.y = Math.max(600, ball.body.position.y);
}
})
I'd really appreciate any help, really stuck with this issue.
Thanks!
I'm still looking for better ways to do it, but my current solution works for most intents and purposes.
The idea is that everytime the user tries to drag the ball beyond the limit, I apply a force that prevents the body from going farther up.
The values need to be fine-tuned on a case-by-case basis but this is what I used:
Matter.Events.on(engine, "afterUpdate", () => {
if(p.mouseIsPressed && p.mouseY < 0.55 * p.height && ball.body.position.y < 0.55 * p.height) {
Matter.Body.applyForce(ball.body, {x: ball.body.position.x, y: ball.body.position.y}, {x: 0, y: -150})
}
Matter.Body.applyForce(ball.body, {x: ball.body.position.x, y: ball.body.position.y}, {x: 0, y: 0})
})
The zeroing out of any force if the ball is within the permissible range removes glitchy movement of the ball after you have tried to drag the ball out, and then it resets.
Note: I tried using setPosition() but that broke the physics of the ball completely. If I resolve that, I'll be editing this answer. Otherwise while the applyForce() values might need to be adjusted more, I'll probably be using that.