Zum Hauptinhalt springen
Echtzeit-Radar & Feeds
Alle RSS Feeds ➔
👥 Community & Social
Windows Tipps & SecurityGrafikkarte vor Überhitzung schützen: So geht’s(25.09.2026 um 08:00 Uhr)
••••••••••
Windows Tipps & SecurityGrafikkarte vor Überhitzung schützen: So geht’s(25.09.2026 um 08:00 Uhr)
••••••••••
Intelligence View
⚡ tsecurity.de Intelligence

Deep Dive: Building "Gravity Paint" - A Tactile Physics Instrument with React, Matter.js, and p5.js

Physics-based browser games are nothing new, but creating something that feels truly organic, interactive, and sensorily satisfying remains a rewarding engineering challenge. In this technical blog post, we look under the hood of Gravity…

0
↗ Quelle (dev.to)
Reagiere als Erste:r — dein Feedback zählt!

Physics-based browser games are nothing new, but creating something that feels truly organic, interactive, and sensorily satisfying remains a rewarding engineering challenge. In this technical blog post, we look under the hood of Gravity Paint – a gravity-aware sandbox puzzle where players paint rigid rope cables to funnel a stream of colorful glass, steel, and bubble marbles into an target collection bucket.



We’ll dissect how to seamlessly combine the state-management of React 19, the performant rigid-body simulations of Matter.js, the smooth visual canvas loops of p5.js, and an in-house Web Audio API synthesizer.






The Three-Headed Architecture: React, P5, & Matter.js



When creating complex interactive canvases, the biggest design issue developers face is Architectural Coordination.





  • React is superb at managing structured data, layout trees, level progression, and sidebars. However, React's virtual-DOM rendering is completely unsuited for high-frequency (60fps) physics steps.


  • Matter.js runs an analytical engine representing worlds, vectors, collisions, shapes, forces, and constraint joints.


  • p5.js (instance-mode) handles graphic pipelines, drawing pixels, mouse inputs, clear frames, and UI animations.



Using these together requires a meticulous boundary of concerns:




+------------------------------------------+
| REACT UI |
| (Campaign Progress, Sound Settings, HUD) |
+--------------------+---------------------+
|
Dispatches Window Event
|
v
+--------------------+---------------------+
| P5.js INSTANCE |
| (Renders pixel world, manages inputs) |
+--------------------+---------------------+
|
Updates Coordinates
|
v
+--------------------+---------------------+
| MATTER.JS WORLD |
| (Evaluates collisions, forces, joints) |
+------------------------------------------+






To prevent memory leaks and coordinate clean slate shifts (like when a level resets or chains are cleared), we wrap the entire canvas setup inside a single React useEffect() ref hook container. Communication across the react wrapper and inner loop coordinates cleanly through custom Window events (CustomEvent), which avoids messy React re-renders interfering with the physics cycle.






The Physics of Paintable Ropes (Chains)



How do we build paintable rope constraints that drape, sag, and sag under weight?



In Matter.js, there is no built-in "rope" body. Instead, a rope is represented as a composite sequence of circular bodies linked sequentially via distance constraints.






1. Tracking Drag Inputs



When a player clicks and drags on the canvas, we record coordinate arrays inside p5:




p.mouseDragged = () => {
const lastPt = tempPoints[tempPoints.length - 1];
const distToPrev = p.dist(p.mouseX, p.mouseY, lastPt.x, lastPt.y);

// Add a new link point only if the mouse has moved far enough (dense brush optimization)
if (distToPrev > 16) {
tempPoints.push({ x: p.mouseX, y: p.mouseY });
}
};









2. Spawning Composite Structures



On mouse release, we convert these floating coordinates into interconnected Matter.js bodies:




const segmentCount = tempPoints.length;
const links: Matter.Body[] = [];
const constraints: Matter.Constraint[] = [];

// Create the link circles
for (let i = 0; i < segmentCount; i++) {
const pt = tempPoints[i];
const link = Matter.Bodies.circle(pt.x, pt.y, 4, {
density: 0.005, // Dictates sag behavior
friction: 0.08,
restitution: 0.4,
collisionFilter: { group: Matter.Body.nextGroup(true) } // Disable self-collisions within the rope
});
links.push(link);
Matter.World.add(world, link);
}

// Interconnect the circles via spring constraints
for (let i = 0; i < segmentCount - 1; i++) {
const con = Matter.Constraint.create({
bodyA: links[i],
bodyB: links[i + 1],
stiffness: 0.85,
length: p.dist(tempPoints[i].x, tempPoints[i].y, tempPoints[i+1].x, tempPoints[i+1].y),
render: { visible: false }
});
constraints.push(con);
Matter.World.add(world, con);
}









The Gravity Snapping Algorithm



If a rope is left unanchored, gravity causes it to plunge into the abyss. To make it a puzzle, we introduce Golden Anchors. These are coordinate locks.



During mouse-down (drag start) and mouse-up (drag end), we check for proximity to preset anchors using traditional Euclidean space calculations:




const findClosestAnchor = (x: number, y: number, radiusThreshold: number = 32) => {
let closest: { x: number; y: number } | null = null;
let minDist = radiusThreshold;

currentLevel.anchors.forEach(anc => {
const d = p.dist(x, y, anc.x, anc.y);
if (d < minDist) {
minDist = d;
closest = anc;
}
});
return closest;
};






If a snap coordinate is found within range:




  1. We align the starting/ending rope link precisely to the Golden Anchor Center.

  2. We create an absolute anchor constraint linking the segment directly to the static Matter world coordinate (represented by a static body).




// Pin rope end firmly to Golden Anchor
const staticAnchorBody = Matter.Bodies.circle(snappedAnchor.x, snappedAnchor.y, 1, { isStatic: true });
Matter.World.add(world, staticAnchorBody);

const anchorConstraint = Matter.Constraint.create({
bodyA: TargetRopeEndBody,
bodyB: staticAnchorBody,
stiffness: 0.95,
length: 0
});
Matter.World.add(world, anchorConstraint);






This creates the gorgeous suspension bridge effect where ropes sway and sag under the impact of rushing marbles!






Creative Sandbox UX: "Clear Chains" Feature



During playtesting, we observed that players wanting to fine-tune their designs became frustrated with full system resets. Resetting cleared their current level collection score and restarted level progress.



To fix this, we implemented Iterative Design Clearing.



We introduced a Clear Chains feature. It targets and clears only the user-painted Matter composite chains, leaving the physics progress of flowing particles, level timers, and collection tally scores completely intact:




// Define clear logic cleanly within Matter physics scope
const handleClearChainsEvent = () => {
if (!world) return;

// Recursively dismount current chains from Matter.World
chains.forEach(c => {
if (c) {
if (c.links) c.links.forEach(l => l && Matter.World.remove(world, l));
if (c.constraints) c.constraints.forEach(con => con && Matter.World.remove(world, con));
}
});
chains = []; // Clear local tracker list
setChainsCount(0); // Sync React state counter
};









Mitigating React Closure Pitfalls in High-Hz Canvas Loops



One of the trickiest bugs solved in this runtime was the Sloppy Run State Capture Freeze.






The Symptom:



When a player dropped more than 5 marbles, a "Sloppy Run! Game Over" card appeared on the screen, prompting a retry. Even though the overlay was active, the marble faucet spigot continued spawning balls, and the fallen ball counter kept increasing, rendering the UI state incorrect.






The Root Cause:



Inside P5's high-frequency p.draw loop (running at 60fps), referencing the React state value showSloppyMessage returns a closure value captured at P5 initialization time. The canvas loop was checking a stale state, meaning it didn't know the game over modal was shown!






The Solution:



We implemented Synchronized Mutable Refs to act as hot-wiring bridges between React and the P5 paint routine:




// 1. Declare state and tracking Ref
const [showSloppyMessage, setShowSloppyMessage] = useState<boolean>(false);
const showSloppyMessageRef = useRef(showSloppyMessage);

// 2. Hot-swap state into hot-ref on state changes securely
useEffect(() => {
showSloppyMessageRef.current = showSloppyMessage;
}, [showSloppyMessage]);

// 3. Inside p5 loop drawer, evaluate strictly from raw Ref:
if (faucetActiveRef.current && activeState === "playing" && !showSloppyMessageRef.current) {
if (p.frameCount % streamSpeedRef.current === 0) {
spawnMarble(); // Faucet spawning stops instantly!
}
}






By querying the Hot-Ref inside p.draw(), the physics loop reacts instantaneously to state changes without experiencing closure lags or forcing canvas re-mounts.









Sound Synthesis: Interactive Web Audio API



To provide sensory satisfaction, Gravity Paint bypasses bulky .mp3 assets in favor of dynamic Web Audio Synthesizers. Whenever a marble collides or drops, we initiate synthetic tone triggers:




export class Synthesizer {
private ctx: AudioContext | null = null;

playPing(index: number) {
if (!this.ctx) this.ctx = new (window.AudioContext || (window as any).webkitAudioContext)();

const osc = this.ctx.createOscillator();
const gain = this.ctx.createGain();

// Choose dynamic pentatonic scaling for musical feedback
const baseFreq = 220;
const pentatonicScales = [1, 1.125, 1.25, 1.5, 1.667, 2, 2.25, 2.5, 3];
const multiplier = pentatonicScales[index % pentatonicScales.length];

osc.frequency.setValueAtTime(baseFreq * multiplier, this.ctx.currentTime);
osc.type = 'triangle'; // Smooth, woody marimba timbre

gain.gain.setValueAtTime(0.2, this.ctx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.001, this.ctx.currentTime + 0.45);

osc.connect(gain);
gain.connect(this.ctx.destination);

osc.start();
osc.stop(this.ctx.currentTime + 0.5);
}
}






This creates a generative visual-instrument experience out of a simple canvas sandbox!



Combining rigid-body physics engines like Matter.js with p5.js layouts inside highly reactive frameworks like React 19 can be challenging. By:




  1. Segregating physics calculations from React renders,

  2. Bridging dynamic loops with hot-ref registers, and

  3. Using decentralized sound generation via the Web Audio API,



we built a high-performance web game. It runs cleanly on everything from standard production servers to sandboxed mobile frames.



Explore the source code, check out the game, and get drawing!






Screenshots



How to play 1



How to play 2



How to play 3



Code and more: https://www.dailybuild.xyz/project/143-gravity-paint

1. Sofort-Triage & Abwehrmaßnahmen

SOC Incident Playbook: Remote Code Execution (RCE) Defense
Syntax validiert (0 Fehler)
title: Detect Exploitation - Deep Dive: Building "Gravity Paint" - A Tactile Physics Instrument with React, Matter.js, and p5.js
id: 1d1a1521-98ac-4461-b365-c0e9dca96884
status: experimental
description: Automatisch generierte SIEM-Erkennungsregel basierend auf CTI Intelligence
references:
  - https://tsecurity.de/
author: iShareStuff CTI Automated Detection Engine
date: 2026-09-25
logsource:
  category: network_connection
  product: any
detection:
  selection:
      DestinationHostname:
        - 'www.dailybuild.xyz'
  condition: selection
falsepositives:
  - Legitime administrative Zugriffe oder Penetrationstests
level: high
tags:
  - attack.initial_access
Syntax validiert (0 Fehler)
rule CTI_Threat_Indicator {
    meta:
        author = "iShareStuff CTI Automated Detection Engine"
        date = "2026-09-25"
        description = "YARA Signature for "
    strings:
        $str = "Deep Dive: Building \"Gravity P" ascii wide
    condition:
        any of them
}
Syntax validiert (0 Fehler)
index=security sourcetype IN ("cisco:asa", "pan:traffic", "zeek_conn", "suricata", "WinEventLog:Security")
(dest_host="www.dailybuild.xyz")
| stats count earliest(_time) as first_seen latest(_time) as last_seen by src_ip, dest_ip, dest_host, signature
| eval first_seen=strftime(first_seen, "%Y-%m-%d %H:%M:%S"), last_seen=strftime(last_seen, "%Y-%m-%d %H:%M:%S")
| sort - count
Syntax validiert (0 Fehler)
destination.domain: ("www.dailybuild.xyz") and event.category: "network"
Syntax validiert (0 Fehler)
CommonSecurityLog
| where DestinationHostName in ("www.dailybuild.xyz")
| summarize EventCount = count(), FirstSeen = min(TimeGenerated), LastSeen = max(TimeGenerated) by SourceIP, DestinationIP, DestinationPort, Activity
| extend DetectionRule = "iShareStuff-CTI-Compiled"
| sort by EventCount desc

2. Cyber Threat Intelligence & Forensik

IoC Intelligence (1 Indikatoren)
www[.]dailybuild[.]xyz
CTI Threat Relationship Graph3 Knoten / 2 Relationen
CVE / Incident Software MITRE ATT&CK CWE Weakness IoC
🎯
MITRE ATT&CK Matrix Navigator 14 Taktiken
Reconnaissance
-
Resource Development
-
Initial Access
Execution
Persistence
-
Privilege Escalation
Defense Evasion
Credential Access
-
Discovery
-
Lateral Movement
-
Collection
-
Command and Control
Exfiltration
-
Impact
tsecurity.de Cognitive Threat RAG
Fokus-Vektor:

Kognitive Analyse für identifizierte Bedrohung: Erhöhte Bedrohungslage im Bereich Deep Dive: Building &quot;Gravity Paint&quot; - A .... Basierend auf 368k Vektor-Korrelationen werden sofortige Isolationsmaßnahmen für betroffene Endpunkte empfohlen.

🛡️ Angriffsfläche & Exposure

Netzwerk/Remote-Zugriff ohne Vorauthentifizierung möglich.

⚡ Empfohlene Sofortmaßnahmen
  • 1. Perimeter-Inspektion: Relevante Portfreigaben und exponierte Endpunkte unverzüglich scannen.
  • 2. Patch-Applikation: Hersteller-Hotfix einspielen oder betroffene Daemons in isolierte DMZ-Segmente überführen.
  • 3. Telemetrie & EDR-Alerts: Prozessaufrufe und Child-Processes auf anomale Shell-Spawns überwachen.
🔗 Semantisch verwandte Zero-Days MariaDB 11.7 VEC
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Deep Dive: Building "Gravity Paint" - A Tactile Physics Instrument with React, Matter.js, and p5.js

Thematisch verwandte Begriffe: Deep, Dive, Building, Gravity · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-61525 | Zammad is a web based open source helpdesk/customer support system. In 7…
Advisory →
tsecurity.de Icon
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag