Skip to content
dev-multiplayer-prediction-shooting logo

Shooting Prediction with Rollback

dev-multiplayer-prediction-shooting

Shooting prediction with optimistic decals and server rollback. Use when implementing shooting mechanics.

SKILL.md

Full skill instructions

Shooting Prediction with Rollback

Shooting mechanics with immediate feedback and server validation.

When to Use

Use when implementing shooting in multiplayer games:

  • FPS weapons
  • Paint/​projectile systems
  • Hit detection
  • Ammo management

Message Structure

// Client sends aim direction + fire command
interface PaintFireMessage {
  type: 'paint_fire';
  direction: { x: number; y: number; z: number }; // Normalized aim vector
  sequence: number; // For rollback reconciliation
}

// Server responds with confirmation/​rejection
interface PaintResultMessage {
  type: 'paint_result';
  sequence: number; // Matches client's fire sequence
  confirmed: boolean;
  reason?: string; // 'no_ink' | 'cooldown' | 'invalid_aim'
}

Client Implementation

import { useRef, useEffect } from 'react';
import { useNetworkManager } from '../​../​services/​NetworkManager';

interface PendingShot {
  id: string;
  direction: Vector3;
  timestamp: number;
  sequence: number;
}

export function PaintGun() {
  const networkManager = useNetworkManager();
  const pendingShotsRef = useRef<PendingShot[]>([]);

  // Optimistic shooting
  function shoot(direction: Vector3) {
    const shotId = `${Date.now()}-${Math.random()}`;
    const sequence = ++shotSequenceRef.current;

    // 1. Spawn paint immediately (optimistic)
    spawnOptimisticDecal(shotId, direction);

    // 2. Store for rollback
    pendingShotsRef.current.push({
      id: shotId,
      direction,
      timestamp: Date.now(),
      sequence,
    });

    // 3. Send to server
    networkManager.send({
      type: 'paint_fire',
      direction,
      sequence,
    });
  }

  // Listen for server confirmation/​rollback
  useEffect(() => {
    const unsubscribe = networkManager.onMessage('paint_result', (result) => {
      handlePaintResult(result);
    });
    return unsubscribe;
  }, []);

  function handlePaintResult(result: PaintResultMessage) {
    const pendingIndex = pendingShotsRef.current.findIndex(
      s => s.sequence === result.sequence
    );

    if (pendingIndex === -1) return;

    const pending = pendingShotsRef.current[pendingIndex];

    if (result.confirmed) {
      // Server confirmed - mark optimistic decal as permanent
      confirmDecal(pending.id);
    } else {
      // Server rejected - rollback (remove optimistic decal)
      rollbackDecal(pending.id);
    }

    pendingShotsRef.current.splice(pendingIndex, 1);
  }

  function spawnOptimisticDecal(id: string, direction: Vector3) {
    // Create temporary decal with "optimistic" flag
    decalManager.spawn({
      id,
      position: calculateImpact(direction),
      team: localTeam,
      optimistic: true, // Mark for potential rollback
    });
  }

  function rollbackDecal(id: string) {
    decalManager.remove(id);
  }

  function confirmDecal(id: string) {
    decalManager.markPermanent(id);
  }
}

Optimistic Decal Manager

interface PendingDecal {
  id: string;
  sequence: number;
  optimistic: boolean;
  confirmed: boolean;
  createdAt: number;
}

export function PaintDecalManager() {
  const pendingDecalsRef = useRef<Map<string, PendingDecal>>(new Map());

  // Spawn optimistic decal (immediate feedback)
  function spawnOptimisticDecal(sequence: number, position: Vector3) {
    const id = `decal-${sequence}`;
    pendingDecalsRef.current.set(id, {
      id,
      sequence,
      optimistic: true,
      confirmed: false,
      createdAt: Date.now(),
    });

    // Create visual immediately (semi-transparent = optimistic)
    createDecalVisual(id, position, { opacity: 0.7 });
  }

  // Confirm decal (server accepted)
  function confirmDecal(sequence: number) {
    const decal = pendingDecalsRef.current.get(`decal-${sequence}`);
    if (decal) {
      decal.confirmed = true;
      decal.optimistic = false;
      updateDecalVisual(decal.id, { opacity: 1.0 }); // Full opacity = confirmed
    }
  }

  // Rollback decal (server rejected)
  function rollbackDecal(sequence: number) {
    const id = `decal-${sequence}`;
    removeDecalVisual(id);
    pendingDecalsRef.current.delete(id);
  }

  // Cleanup old optimistic decals (in case server never responds)
  useFrame(() => {
    const now = Date.now();
    for (const [id, decal] of pendingDecalsRef.current) {
      if (decal.optimistic && now - decal.createdAt > 2000) {
        rollbackDecal(decal.sequence);
      }
    }
  });
}

Server Validation

// server/​systems/​ProjectileSystem.ts
export class ProjectileSystem {
  private projectiles: PaintProjectile[] = [];

  processFireMessage(client: Client, data: FireMessage) {
    const player = this.room.state.players.get(client.sessionId);
    if (!player) return;

    // 1. Validate ammo (server-enforced)
    if (player.ink <= 0) {
      this.sendReject(client, data.sequence, 'no_ink');
      return;
    }

    // 2. Validate fire rate (server-enforced, 600 RPM = 100ms cooldown)
    const now = Date.now();
    if (now - player.lastShotTime < 100) {
      this.sendReject(client, data.sequence, 'cooldown');
      return;
    }

    // 3. Validate aim direction (prevent packet spam exploits)
    const aimLength = Math.sqrt(
      data.direction.x ** 2 +
      data.direction.y ** 2 +
      data.direction.z ** 2
    );
    if (aimLength > 1.1 || aimLength < 0.9) {
      this.sendReject(client, data.sequence, 'invalid_aim');
      return;
    }

    // Create projectile SERVER-SIDE
    const projectile: PaintProjectile = {
      id: `proj-${client.sessionId}-${data.sequence}`,
      x: player.x,
      y: player.y + 1.5,
      z: player.z,
      dx: data.direction.x * 25, // 25 m/​s
      dy: data.direction.y * 25,
      dz: data.direction.z * 25,
      owner: client.sessionId,
      team: player.team,
      sequence: data.sequence,
    };

    this.projectiles.push(projectile);
    player.ink -= 1;
    player.lastShotTime = now;

    // Notify client that shot was accepted
    this.sendConfirm(client, data.sequence);
  }

  update(dt: number) {
    const deltaTime = dt / 1000;

    for (let i = this.projectiles.length - 1; i >= 0; i--) {
      const proj = this.projectiles[i];

      // Move projectile
      proj.x += proj.dx * deltaTime;
      proj.y += proj.dy * deltaTime;
      proj.z += proj.dz * deltaTime;

      // Apply gravity
      proj.dy -= 9.8 * deltaTime;

      // Check collision
      if (this.checkCollision(proj)) {
        this.spawnPaintDecal(proj);
        this.broadcastPaintEvent(proj);
        this.projectiles.splice(i, 1);
      } else if (proj.y < 0) {
        // Below ground
        this.projectiles.splice(i, 1);
      }
    }
  }

  sendConfirm(client: Client, sequence: number) {
    client.send({
      type: 'paint_result',
      sequence,
      confirmed: true,
    });
  }

  sendReject(client: Client, sequence: number, reason: string) {
    client.send({
      type: 'paint_result',
      sequence,
      confirmed: false,
      reason,
    });
  }
}

Grid-Based Paint Coverage

// 5x5 unit grid cells for performance
interface PaintGrid {
  [cellKey: string]: {
    orange: number; // Orange paint count
    blue: number;   // Blue paint count
  };
}

function getCellKey(x: number, z: number): string {
  const cellX = Math.floor(x / 5);
  const cellZ = Math.floor(z / 5);
  return `${cellX},${cellZ}`;
}

function addPaintToGrid(grid: PaintGrid, x: number, z: number, team: 'orange' | 'blue') {
  const key = getCellKey(x, z);
  if (!grid[key]) {
    grid[key] = { orange: 0, blue: 0 };
  }
  grid[key][team]++;
}

function getPaintCoverage(grid: PaintGrid, team: 'orange' | 'blue'): number {
  return Object.values(grid).reduce(
    (sum, cell) => sum + cell[team],
    0
  );
}

Validation Checklist

function validateFireMessage(player: PlayerState, data: PaintFireMessage): string | null {
  // Validate ammo
  if (player.ink <= 0) return 'no_ink';

  // Validate fire rate
  const now = Date.now();
  if (now - player.lastShotTime < 100) return 'cooldown';

  // Validate aim direction
  const aimLength = Math.sqrt(
    data.direction.x ** 2 +
    data.direction.y ** 2 +
    data.direction.z ** 2
  );
  if (aimLength > 1.1 || aimLength < 0.9) return 'invalid_aim';

  return null; // Valid
}

Common Mistakes

❌ Wrong✅ Right
No optimistic feedbackSpawn decal immediately
Server accepts all shotsValidate ammo, cooldown, aim
No rollback mechanismRemove rejected effects
Cleanup never happensTimeout old optimistic decals
Trust client hit detectionServer-authoritative hit validation

Reference

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View