You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

101 lines
2.9 KiB

import React from "react";
import Sketch from "react-p5";
let positions = [];
let initialPos;
let playerPath = [];
let stepX;
let stepY;
let numCols = 50;
let numRows = 25;
export default (props) => {
const setup = (p5, canvasParentRef) => {
p5.createCanvas(1000, 500).parent(canvasParentRef);
const setupGrid = () => {
stepX = p5.width / numCols; //to make sure they are evenly spaced, we divide the width and height by numberOfColumns
stepY = p5.height / numRows; //and numberOfRows respectively
for (let x = 0; x < p5.width; x += stepX) {
//start at the first column, where x = 0
for (let y = 0; y < p5.height; y += stepY) {
//go through all the rows (y = 0, y = yStep * 1, y = yStep * 2, etc.)
const p = p5.createVector(x, y); //we create a vector at this location
positions.push(p); // and then we put the vector into the array
}
//at the end of the inner for loop, we go back to the first loop, and we increment x
//now our column is going to b x = xStep*1, and we populate all the rows with the inner for loop
//and again, and again until x > width
}
};
const setupPlayer = () => {
initialPos = p5.createVector(5, 5);
playerPath.push(p5.createVector(1, 0));
playerPath.push(p5.createVector(1, 1));
playerPath.push(p5.createVector(1, 1));
playerPath.push(p5.createVector(0, 1));
};
setupGrid();
setupPlayer();
};
const draw = (p5) => {
const drawGrid = () => {
p5.push();
p5.fill(100, 100, 100);
p5.noStroke();
for (let i = 0; i < positions.length; i++) {
//go through all our positions
p5.ellipse(positions[i].x, positions[i].y, 2, 2); //put a circle at each of them
}
p5.pop();
};
const drawPlayer = () => {
p5.push();
p5.fill(255, 0, 0); // Red
p5.noStroke();
// Need to clone here to not override initial position
let currentPos = { ...initialPos };
// Draw initial position
p5.ellipse(currentPos.x * stepX, currentPos.y * stepY, 5, 5);
for (let pos of playerPath) {
const previous = { ...currentPos };
currentPos.x += pos.x;
currentPos.y += pos.y;
p5.push();
p5.stroke(150);
p5.line(previous.x * stepX, previous.y * stepY, currentPos.x * stepX, currentPos.y * stepY);
p5.pop();
p5.ellipse(currentPos.x * stepX, currentPos.y * stepY, 5, 5);
}
p5.pop();
};
drawGrid();
drawPlayer();
};
return <Sketch setup={setup} draw={draw} />;
};