Predict projectile motion
See original GitHub issueI am using Phaser3 to make an Angry Birds like game, where I throw a ball. I am not totally sure I need this feature yet in my game, but I was trying to find the prediction of the trajectory of the ball, after I set a velocity to it. I saw that the matterj.s code does first this on the body update:
body.force.x += body.mass * gravity.x * gravityScale;
and then this on the engine:
body.velocity.y = (velocityPrevY * frictionAir * correction) + (body.force.y / body.mass) * deltaTimeSquared;
When the slingshot fires, and the drag ends, I do:
gameObject.setVelocity((gameObject.startPos.x - gameObject.x) * SPEED,
(gameObject.startPos.y - gameObject.y) * SPEED)
While dragging occurs, I try to predict the various positions, with my knowledge and memory of school-level physics.
...
gameObject.x = dragX;
gameObject.y = dragY;
const velocityX = (gameObject.startPos.x - dragX) * SPEED;
const velocityY = (gameObject.startPos.y - dragY) * SPEED;
let index = 1;
for (let trajectoryPoint of trajectoryPoints.getChildren()) {
trajectoryPoint.x = gameObject.x + index * velocityX;
trajectoryPoint.y = gameObject.y + index * velocityY + GRAVITY * index * (index + 1) / 2;
index++;
}
...
with GRAVITY
being the matter.js gravity, and gameObject
being the ball. This gives me a nice trajectory, similar to what matter.js does, but not quite there… Any idea what I am missing?
Issue Analytics
- State:
- Created 6 years ago
- Reactions:1
- Comments:7 (3 by maintainers)
Top GitHub Comments
@liabru and for whoever else comes across this, I just figured it out! You need to also clear the forces, at the end of the update, as this is what
Engine.update
does, it calls_bodiesClearForces
at the end. So, you need to do 3 main things:That doesn’t look correct to me, you’re missing the
airFriction
term for one thing?I’d suggest the easiest way to do this is to take note of the projectile’s initial position and angle, then literally call
Body.update(...)
on it in a loop, taking a clone of itsbody.position
vectors and putting them into an array, then restoring it back to the original position?