xxxxxxxxxx
/**
* Made with p5play!
* https://p5play.org
*/
// Learn more about p5play here -> https://p5play.org/learn
// Testing out a Color
let instructions = 'Tap to create a new sprite, drag to throw it!';
let box;
let greenBoxes, redBoxes, blueBoxes, blackBoxes, ground;
let colors = [];
let boxGroups = [];
let colorIndex = 3;
// For transitioning colors using lerpColor function, we need
// two colors, and a "t" variable that we move from 0 to 1 over time
let newColor, prevColor, t, lerpSpeed;
function setup() {
// creates a canvas that fills the screen
new Canvas();
world.gravity.y = 9.81;
ground = new Sprite (canvas.w/2, canvas.h/2, canvas.w, 50, "static");
greenBoxes = new Group();
greenBoxes.color = color("green");
redBoxes = new Group();
redBoxes.color = color("red");
blueBoxes = new Group();
blueBoxes.color = color("blue");
blackBoxes = new Group();
blackBoxes.color = color("black");
colorMode("HSB");
colors = [color("red"), color("green"), color("blue"), color("black")];
boxGroups = [redBoxes, greenBoxes, blueBoxes, blackBoxes]
prevColor = color("white");
newColor = color("black");
t = 0;
lerpSpeed = 0.1;
}
function draw() {
clear(); // try removing this line and see what happens!
textSize(18);
textAlign(CENTER);
fill(200);
text(instructions, canvas.w / 2, canvas.h / 2);
if (mouse.presses()) {
if (floor(random(0, 3)) === 0) {
box = new redBoxes.Sprite(mouse.x, mouse.y, 30, 30);
} else if (floor(random(0, 3)) === 1) {
box = new greenBoxes.Sprite(mouse.x, mouse.y, 30, 30);
} else if (floor(random(0, 3)) === 2) {
box = new blueBoxes.Sprite(mouse.x, mouse.y, 30, 30);
} else {
box = new blackBoxes.Sprite(mouse.x, mouse.y, 30, 30);
}
}
if (mouse.dragging()) {
box.moveTowards(mouse); // throw the box!
}
// if the user didn't throw the box,
// then give it a random speed and direction
if (mouse.released() && !mouse.dragged()) {
box.speed = random(0, 5);
box.direction = random(0, 360);
}
if (kb.presses("up")) {
// Undo the previous overlap
ground.collides(boxGroups[colorIndex]);
prevColor = colors[colorIndex];
colorIndex++;
if (colorIndex >= colors.length) {
colorIndex = 0;
}
newColor = colors[colorIndex];
t = 0;
} else if (kb.presses("down")) {
// Undo the previous overlap
ground.collides(boxGroups[colorIndex]);
prevColor = colors[colorIndex];
colorIndex--;
if (colorIndex <= 0) {
colorIndex = colors.length-1;
}
newColor = colors[colorIndex];
t = 0;
}
if (t < 1) {
t += lerpSpeed;
}
ground.color = lerpColor(prevColor, newColor, t);
// If the ground color equals the box color, let the box group overlap
ground.overlaps(boxGroups[colorIndex]);
// by default, all sprites are drawn by p5play
// after the end of the draw function
}