xxxxxxxxxx
67
let gameShader;
let numObjects = 1000; // MUST MATCH SHADER VALUE!
let gameObjects = []; // array of circle positions and radius
// load in the shader
function preload() {
gameShader = loadShader('game.vert', 'game.frag');
}
function setup() {
createCanvas(600, 600, WEBGL);
shader(gameShader);
createGameObjects();
}
function draw() {
// Update game obeject positions
gameObjects.forEach(obj => {
obj.x += random(-1, 1);
obj.y += random(-1, 1);
obj.z += random(-1, 1);
obj.x = constrain(obj.x, 0, width);
obj.y = constrain(obj.y, 0, width);
obj.z = constrain(obj.z, 5, 10);
});
// Tell the shader the resolution of the screen
gameShader.setUniform("screen_res", [width, height]);
// Set game objects in shader
gameShader.setUniform("game_objects", convertObjectsToUniform());
// Run shader
rect(-width/2, -height/2, width, height);
}
// Create a bunch of p5.Vectors for each object
// x, y = position, z = circle radius
function createGameObjects() {
gameObjects = [];
for(let i = 0; i < numObjects; i ++) {
const x = random(width); // random x location
const y = random(height); // random y location
const r = random(5, 10); // random circle radius
gameObjects.push(createVector(x, y, r));
}
}
// The game_objects uniform is defined as
// an array of vec3s in the shader
// however to pass them in, we need a single array
// with all the values in them
// So this function just produces an array
// with all the values in order
function convertObjectsToUniform() {
let numArray = [];
gameObjects.forEach(obj => {
numArray.push(obj.x, obj.y, obj.z);
});
return numArray;
}