Aller au contenu principal

The Simulation

The simulation world is the container for your physics environment. It manages all the particles and constraints, and is responsible for stepping the simulation forward in time.

Creating a Simulation

This is the first step to get anything running.

In React, you create a simulation world using the <VerletCanvas> component. It requires width and height props to define its boundaries.

import React from 'react';
import { VerletCanvas } from 'verlet-react';

const App = () => {
return (
<VerletCanvas width={600} height={400}>
{/* Your particles and constraints will go here */}
</VerletCanvas>
);
};

Configuring the Simulation

You can customize the global physics properties of the simulation, like gravity and friction.

You pass an options object to the <VerletCanvas> component. The simulation will automatically update if you change this object.

import { Vec2 } from 'verlet-engine';

const simOptions = {
gravity: new Vec2(0, 0.5),
friction: 0.98,
solverIterations: 15,
};

const App = () => {
return (
<VerletCanvas width={600} height={400} options={simOptions}>
{/* ... */}
</VerletCanvas>
);
};

Available Options

  • gravity (Vec2): A vector representing the global gravity. Default is new Vec2(0, 0.2).
  • friction (number): The air friction applied to all particles. 1.0 means no friction. Default is 0.99.
  • groundFriction (number): The friction applied when a particle is on the ground. Default is 0.8.
  • restitution (number): The "bounciness" of particles when they hit the boundaries. 1.0 is a perfectly elastic collision. Default is 0.2.
  • solverIterations (number): The number of times the constraint solver runs per frame. More iterations lead to more rigid and stable simulations but require more processing power. Default is 8.

Updating the Simulation

To create motion, the simulation must be advanced on each frame.

The <VerletCanvas> handles this automatically. It uses an internal requestAnimationFrame loop to update the simulation and re-render the canvas whenever a change occurs. You do not need to do anything.

Adding Objects

You add objects declaratively by placing them as children of <VerletCanvas>. This is the standard React way of building a scene.

import { VerletCanvas, Point, Cloth } from 'verlet-react';
import { Vec2 } from 'verlet-engine';

const App = () => {
return (
<VerletCanvas width={600} height={400}>
{/* Add a single point */}
<Point id="p1" pos={new Vec2(100, 100)} />

{/* Add a complex composite */}
<Cloth
origin={new Vec2(200, 100)}
width={150}
height={100}
segments={12}
/>
</VerletCanvas>
);
};