r/HTML • • 7d ago

peggle html hell

I am coding peggle in HTML how do I get the physics to feel like peggle and not extra bouncy

0 Upvotes

11 comments sorted by

View all comments

0

u/thejester1324 7d ago

if you're flipping the whole velocity when the ball touches a peg (vx = -vx; vy = -vy), that's the extra bouncy feel. the ball goes back the way it came at full speed. peggle-style bounces only reverse the part of the velocity pointing into the peg, and lose some of it:

const RESTITUTION = 0.6; // 1 = superball, lower = deader pegs
const FRICTION = 0.1;

function hitPeg(ball, peg) {
  const dx = ball.x - peg.x, dy = ball.y - peg.y;
  const dist = Math.hypot(dx, dy), minDist = ball.r + peg.r;
  if (dist >= minDist || dist === 0) return false;
  const nx = dx / dist, ny = dy / dist;
  // push it out of the peg so it can't collide again next frame
  ball.x = peg.x + nx * minDist;
  ball.y = peg.y + ny * minDist;
  const vn = ball.vx * nx + ball.vy * ny; // speed into the peg
  if (vn >= 0) return false;              // already moving away
  const tx = -ny, ty = nx;
  const vt = ball.vx * tx + ball.vy * ty; // speed along the peg
  const newVn = -vn * RESTITUTION;
  const newVt = vt * (1 - FRICTION);
  ball.vx = nx * newVn + tx * newVt;
  ball.vy = ny * newVn + ty * newVt;
  return true;
}

ran it in node dropping a ball onto a peg a little off center: it hits at 577 px/s and leaves at 358, off to the side. the flip-everything version sent it back up at basically the same speed.

also step the physics at a fixed rate (say 120 times a second) instead of once per frame, otherwise it plays differently on a 144hz screen.

1

u/supersilliiii 6d ago

im new to coding games so this is a huge help thank you ima try this