← Back to Blog
DevelopmentOctober 1, 2025·10 min read

Building a Physics Engine for Desktop Pets

A convincing desktop pet needs convincing physics. Here's the minimal approach I used for Dhiva Pet.

Core State

const pet = {
  x: 100, y: 500,
  vx: 0, vy: 0,
  w: 120, h: 120,
  onGround: true
};

const GRAVITY = 1800;
const JUMP_FORCE = 700;
const WALK_SPEED = 80;

The Update Loop

function step(dt) {
  pet.vy += GRAVITY * dt;
  pet.x += pet.vx * dt;
  pet.y += pet.vy * dt;

  const floorY = H - pet.h - 8;
  if (pet.y >= floorY) {
    pet.y = floorY;
    if (pet.vy > 200 && !pet.onGround) setState('land');
    pet.vy = 0;
    pet.onGround = true;
  } else {
    pet.onGround = false;
  }
}

Delta-time based integration keeps physics consistent regardless of frame rate. Always clamp dt to prevent huge jumps after tab switching.

Screen Boundaries

Horizontal collision is simple — clamp to 0 and W - w, and flip walking direction. Ceiling collision prevents the pet from escaping upward after a hard jump.

Rope Swing (Bonus)

For Monkey and Spiderman, I added a pendulum simulation:

this.swingAngle += this.swingSpeed * dt;
this.x = anchorX + Math.sin(this.swingAngle) * length - w/2;
this.y = anchorY + Math.cos(this.swingAngle) * length - h/2;

When the pet releases, tangential velocity is applied:

const vTan = swingSpeed * length;
this.vx = vTan * Math.cos(swingAngle);
this.vy = -vTan * Math.sin(swingAngle);