HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<div id="flock"></div>
html, body {
margin: 0;
padding: 0;
background: #f5f5f5;
color: #333;
text-align: center;
font-family: Arial, Helvetica, sans-serif;
width: 100%;
height: 100%;
overflow: hidden;
}
h1, h2, h3, h4 {
font-weight: normal;
}
#flock {
width: 100%;
height: 100%;
display: inline-block;
margin: 0;
}
footer {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
text-align: center;
color: #666;
padding: 0.5em 1em;
}
a, a:link, a:focus, a:visited {
color: #ccc;
text-decoration: none;
}
a:hover {
color: #fff;
}
declare var PIXI: any;
declare var Stats: any;
type Options = {
containerId: string,
boidLength: number,
boidHeight: number,
number: number,
speed: number,
cohesionRadius: number,
separationRadius: number,
alignmentRadius: number,
predatorRadius: number,
cohesionForce: number,
separationForce: number,
alignmentForce: number,
predatorForce: number,
obstacleForce: number,
};
type Position = {
x: number,
y: number,
};
class Renderer {
private app: PIXI.Application;
private container: PIXI.ParticleContainer;
private boidTexture: PIXI.Texture;
private stats: Stats;
private boids: PIXI.Sprite[] = [];
constructor(private options: Options) {
this.app = new PIXI.Application({
resizeTo: window,
resolution: devicePixelRatio,
autoDensity: true,
backgroundColor: 0xf5f5f5,
});
this.container = new PIXI.ParticleContainer(this.options.number, {
position: true,
rotation: true,
tint: true,
});
this.app.stage.addChild(this.container);
// Prepare the boid texture for sprites
const graphics = new PIXI.Graphics();
graphics.beginFill(0xcccccc);
graphics.lineStyle(0);
graphics.drawPolygon([
new PIXI.Point(this.options.boidLength / 2, this.options.boidHeight),
new PIXI.Point(0, 0),
new PIXI.Point(this.options.boidLength, 0),
]);
graphics.endFill();
const region = new PIXI.Rectangle(0, 0, options.boidLength, options.boidHeight);
this.boidTexture = this.app.renderer.generateTexture(graphics, 1, 1, region);
this.boidTexture.defaultAnchor.set(0.5, 0.5);
// Render the app
document.getElementById(this.options.containerId).appendChild(this.app.view);
}
public start() {
const maxX = this.app.screen.width;
const maxY = this.app.screen.height;
for (let i = 0; i < this.options.number; i++) {
const boid = new PIXI.Sprite(this.boidTexture);
boid.x = Math.floor(Math.random() * maxX);
boid.y = Math.floor(Math.random() * maxY);
boid.pivot.set(this.options.boidLength / 2, this.options.boidHeight)
boid.anchor.set(0.5, 0.5)
boid.rotation = Math.random() * Math.PI * 2;
this.container.addChild(boid);
this.boids.push(boid);
}
// Listen for animate update
this.app.ticker.add((delta) => {
this.updateBoids(delta);
});
}
private updateBoids(delta: number) {
const maxX = this.app.screen.width;
const maxY = this.app.screen.height;
const children = this.boids.length;
for (let i = 0; i < children; i++) {
const boid = this.boids[i];
// Forces that determine flocking
let f_cohesion: number = 0; // steer towards average position of neighbours (long range attraction)
let f_separation: number = 0; // avoid crowding neighbours (short range repulsion)
let f_alignment: number = 0; // steer towards average heading of neighbours
let f_predators: number = 0; // avoid predators
let f_obstacles: number = 0; // avoid obstacles (same as predators but with less margin)
// Find important neighbours
const cohesionNeighbours: PIXI.Sprite[] = [];
const separationNeighbours: PIXI.Sprite[] = [];
const alignmentNeighbours: PIXI.Sprite[] = [];
// const enemiesNear = [];
// Iterate over the rest of the boids
for (let a = 0; a < children; a++) {
if (a === i) {
continue;
}
const neighbour = this.boids[a];
const d = Renderer.distance(boid, neighbour);
if (d < this.options.separationRadius) {
separationNeighbours.push(neighbour);
}
if (d < this.options.alignmentRadius) {
alignmentNeighbours.push(neighbour);
}
if (d < this.options.cohesionRadius) {
cohesionNeighbours.push(neighbour);
}
}
boid.tint = 0x333333;
// Calculate forces
if (separationNeighbours.length > 0) {
f_separation = Renderer.getNeighboursRotation(separationNeighbours, boid) + Math.PI;
}
if (alignmentNeighbours.length > 0) {
boid.tint = 0x9dd60b;
}
if (cohesionNeighbours.length + separationNeighbours.length + alignmentNeighbours.length < 1) {
boid.tint = 0xcccccc;
}
if (alignmentNeighbours.length > 0) {
f_alignment = Renderer.getNeighboursRotation(alignmentNeighbours, boid);
}
if (cohesionNeighbours.length > 0) {
f_cohesion = Renderer.getNeighboursRotation(cohesionNeighbours, boid);
}
// set the mouse as an enemy
const mouseCoords = this.app.renderer.plugins.interaction.mouse.global;
const mouseDistance = Renderer.distance(mouseCoords, boid);
if (mouseDistance < this.options.predatorRadius) {
boid.tint = 0xeb0000;
f_predators = Renderer.getRotation(mouseCoords.x, mouseCoords.y, boid) + Math.PI;
}
// REF:
// https://github.com/rafinskipg/birds/blob/master/app/scripts/models/birdsGenerator.js
// REF2
// Reynolds, Craig (1987). "Flocks, herds and schools: A distributed behavioral model.". SIGGRAPH '87: Proceedings of the 14th annual conference on Computer graphics and interactive techniques. Association for Computing Machinery
// Calculate the new direction of flight
boid.rotation = boid.rotation +
this.options.cohesionForce * f_cohesion / 100 +
this.options.separationForce * f_separation / 100 +
this.options.alignmentForce * f_alignment / 100 +
this.options.predatorForce * f_predators / 100 +
this.options.obstacleForce * f_obstacles / 100;
// Now use the angle and the speed to calculate dx and dy
const dx = Math.sin(boid.rotation) * this.options.speed;
const dy = Math.cos(boid.rotation) * this.options.speed;
boid.x -= dx * delta;
boid.y += dy * delta;
// Wrap around
if (boid.x <= 0) {
boid.x = maxX - 1;
} else if (boid.x >= maxX) {
boid.x = 1;
}
if (boid.y <= 0) {
boid.y = maxY - 1;
} else if (boid.y >= maxY) {
boid.y = 1;
}
}
}
private static random(min: number, max: number) {
return min + Math.random() * (max - min);
}
private static getNeighboursRotation(neighbours: Array<PIXI.Sprite>, boid: PIXI.Sprite) {
if (neighbours.length < 1) {
return 0;
}
// [meanX, meanY] is the center of mass of the neighbours
const meanX = Renderer.arrayMean(neighbours, (boid: PIXI.Sprite) => boid.x);
const meanY = Renderer.arrayMean(neighbours, (boid: PIXI.Sprite) => boid.y);
return Renderer.getRotation(meanX, meanY, boid);
}
private static getRotation(meanX: number, meanY: number, boid: PIXI.Sprite) {
// Vector from boid to mean neighbours
const mean_dx = meanX - boid.x;
const mean_dy = meanY - boid.y;
// Diff between angle of the vector from boid to the mean neighbours and current direction
return Math.atan2(mean_dy, mean_dx) - boid.rotation;
}
private static distance(p1: Position, p2: Position) {
// Approximation by using octagons approach
const dx = Math.abs(p2.x - p1.x);
const dy = Math.abs(p2.y - p1.y);
return 1.426776695 * Math.min(0.7071067812 * (dx + dy), Math.max(dx, dy));
}
private static arrayMean(arr: Array<any>, getKey: Function) {
let result = 0;
for (let i = 0; i < arr.length; i++) {
result += getKey(arr[i]);
}
result /= arr.length;
return result;
}
}
const options: Options = {
containerId: 'flock',
boidLength: 5,
boidHeight: 10,
number: 75,
speed: 3,
cohesionRadius: 130,
alignmentRadius: 25,
separationRadius: 10,
predatorRadius: 100,
cohesionForce: 90,
separationForce: 5,
alignmentForce: 10,
predatorForce: 60,
obstacleForce: 20,
};
// Setup the Renderer
const renderer = new Renderer(options);
renderer.start();
Also see: Tab Triggers