How can I make the background transparent in P5.js, but still keep the same effect? - image

I have a P5.js art, but when I remove the background, the effect changes. I'd like to remove the background but keep the effect the same. The reason for this is because I plan to overlay this on top of another canvas.
The line I'd like to remove is this: background(30); However, when I remove it, the effect becomes different.
The full code can be found here: https://editor.p5js.org/timexer/sketches/Rbbo72xVi
class Particle {
constructor(){
this.pos = createVector(width/2,height/2)
this.vel = createVector(0,0)
this.acc = p5.Vector.random2D().normalize()
this.r = map(this.pos.x, 0, width, 255, 0)
this.g = map(this.pos.y, 0, height, 0, 255)
this.b = map(dist(width / 2, height / 2, this.pos.x, this.pos.y), 0, width/2, 0, 255)
this.alpha = 255
}
update(){
var m = map(sin(frameCount), -1, 1, 0.3, 0.6)
this.acc.mult(m)
this.vel.add(this.acc)
this.pos.add(this.vel)
this.r = map(this.pos.x, 0, width, 255, 0)
this.g = map(this.pos.y, 0, height, 0, 255)
this.b = map(dist(width / 2, height / 2, this.pos.x, this.pos.y), 0, width, 0, 255)
if ( dist(width / 2, height / 2, this.pos.x, this.pos.y) > 80){
this.alpha -= 5
}
}
show(){
noStroke()
fill(this.r, this.g, this.b, this.alpha)
ellipse(this.pos.x, this.pos.y, 2)
}
}
var particles = []
function setup() {
createCanvas(800, 800);
angleMode(DEGREES)
}
function draw() {
background(30);
for(var i = 0; i <10; i++){
p = new Particle()
particles.push(p)
}
for(var i = 0; i < particles.length ; i++){
if(particles[i].alpha > 0){
particles[i].update()
particles[i].show()
}else{
particles.splice(i,1)
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>

Instead of calling background(30) call clear()
var particles = []
function setup() {
createCanvas(windowWidth, windowHeight);
angleMode(DEGREES)
}
function draw() {
clear();
for (var i = 0; i < 10; i++) {
const p = new Particle()
particles.push(p)
}
for (var i = 0; i < particles.length; i++) {
if (particles[i].alpha > 0) {
particles[i].update()
particles[i].show()
} else {
particles.splice(i, 1)
}
}
}
class Particle {
constructor() {
this.pos = createVector(width / 2, height / 2)
this.vel = createVector(0, 0)
this.acc = p5.Vector.random2D().normalize()
this.r = map(this.pos.x, 0, width, 255, 0)
this.g = map(this.pos.y, 0, height, 0, 255)
this.b = map(dist(width / 2, height / 2, this.pos.x, this.pos.y), 0, width / 2, 0, 255)
this.alpha = 255
}
update() {
var m = map(sin(frameCount), -1, 1, 0.3, 0.6)
this.acc.mult(m)
this.vel.add(this.acc)
this.pos.add(this.vel)
this.r = map(this.pos.x, 0, width, 255, 0)
this.g = map(this.pos.y, 0, height, 0, 255)
this.b = map(dist(width / 2, height / 2, this.pos.x, this.pos.y), 0, width, 0, 255)
if (dist(width / 2, height / 2, this.pos.x, this.pos.y) > 80) {
this.alpha -= 5
}
}
show() {
noStroke()
fill(this.r, this.g, this.b, this.alpha)
ellipse(this.pos.x, this.pos.y, 2)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>

Related

Swap image sprite in HTML5 Canvas game

Trying to add basically different looking zombie. Is there a way to just swap the sprite or would I have to keep adding the code for class, scrolling etc.
class Zombie1 {
constructor({
position,
velocity,
distance = {
limit: 50,
traveled: 0
}
}) {
this.position = {
x: position.x,
y: position.y
}
this.velocity = {
x: velocity.x,
y: velocity.y
}
this.width = 97.49
this.height = 150
this.image = createImage(spriteZombie1)
this.frames = 0
this.distance = distance
}
draw() {
// c.fillStyle = 'red'
// c.fillRect(this.position.x, this.position.y, this.width, this.height)
c.drawImage(
this.image,
130 * this.frames,
0,
130,
150,
this.position.x,
this.position.y,
this.width,
this.height
)
}
update() {
this.frames++
if (this.frames >= 58) this.frames = 0
this.draw()
this.position.x += this.velocity.x
this.position.y += this.velocity.y
this.enemies = [];
if (this.position.y + this.height + this.velocity.y <= canvas.height)
this.velocity.y += gravity
// walk the zombie back and forth
this.distance.traveled += Math.abs(this.velocity.x)
if (this.distance.traveled > this.distance.limit) {
this.distance.traveled = 0
this.velocity.x = -this.velocity.x
}
}
}
zombies1 = [
new Zombie1({
position: {
x: 4000,
y: -950
},
velocity: {
x: -1,
y: 0
},
distance: {
limit: 7,
traveled: 0
}
}),
I have no problem adding more classes, it gets tedious and clutters the code. It won't let me post anymore code but that seems to be the important ones, other than importing the sprites.

p5.js: Random movement of drawing tool

I coded this drawing tool:
var a = 0;
function setup() {
createCanvas(windowWidth, windowHeight);
background(0, 0, 255);
}
function draw() {
fill(0, 255, 255, random(255));
translate(mouseX, mouseY);
rotate(a);
textSize(120);
textAlign(CENTER, CENTER);
text('*', 0, 0);
rotate(a);
a = a + 0.08;
}
<script src="https://cdn.jsdelivr.net/npm/p5#1.4.1/lib/p5.js"></script>
Now I would like to have a movement, without doing it with the cursor. I have thought about something like this:
var a;
function centerCanvas() {
var x = (windowWidth - width) / 2;
var y = (windowHeight - height) / 2;
a.position(x, y);
}
function setup() {
a = createCanvas(windowHeight, windowHeight);
centerCanvas();
}
function draw() {
fill(0, 255, 255, random(255));
var x =
windowHeight / 2 +
sin(frameCount * 0.01) * cos(frameCount * 0.04) * windowHeight / 3;
var y =
windowHeight / 2 +
cos(frameCount * 0.01) * sin(frameCount * 0.04) * windowHeight / 3;
rotate(a);
textSize(120);
textAlign(CENTER, CENTER);
text('*', 0, 0);
rotate(a);
a = a + 0.08;
}
<script src="https://cdn.jsdelivr.net/npm/p5#1.4.1/lib/p5.js"></script>
Unfortunately, it doesn't work. It also would be cool if the movement would be random inside the canvas. Does anyone know how to do it?
This (almost) worked for me:
let wander;
function setup() {
createCanvas(windowWidth, windowHeight);
background(0, 0, 0);
wander = new Vehicle(0, 0);
}
function draw() {
wander.wander();
wander.update();
wander.edges();
wander.show();
}
class Vehicle {
constructor(x, y) {
this.pos = createVector(x, y);
this.vel = createVector(1, 0);
this.acc = createVector(0, 0);
this.maxSpeed = 4;
this.maxForce = 0.2;
this.r = 16;
this.wanderTheta = PI / 2;
this.xoff = 0;
}
wander() {
let angle = noise(this.xoff) * TWO_PI * 2;
let steer = p5.Vector.fromAngle(angle);
steer.setMag(this.maxForce);
this.applyForce(steer);
this.xoff += 0.01;
}
applyForce(force) {
this.acc.add(force);
}
update() {
this.vel.add(this.acc);
this.vel.limit(this.maxSpeed);
this.pos.add(this.vel);
this.acc.set(0, 0);
}
show() {
stroke(255);
strokeWeight(2);
fill(255);
push();
translate(this.pos.x, this.pos.y);
rotate(this.vel.heading());
textAlign(CENTER, CENTER);
textSize(120);
fill(0, 255, 255, random(255));
text("*", 0, 0);
pop();
}
edges() {
let hitEdge = false;
if (this.pos.x > width + this.r) {
this.pos.x = -this.r;
hitEdge = true;
} else if (this.pos.x < -this.r) {
this.pos.x = width + this.r;
hitEdge = true;
}
if (this.pos.y > height + this.r) {
this.pos.y = -this.r;
hitEdge = true;
} else if (this.pos.y < -this.r) {
this.pos.y = height + this.r;
hitEdge = true;
}
}
}
<script src="https://cdn.jsdelivr.net/npm/p5#1.4.1/lib/p5.js"></script>
Using P5.js's noise function is a really accurate way to represent wandering. With a little tinkering you can get the effect you want.
EDIT
This is your (debugged) code:
let a;
let r;
function centerCanvas() {
var x = (windowWidth - width) / 2;
var y = (windowHeight - height) / 2;
a.position(x, y);
}
function setup() {
a = createCanvas(windowHeight, windowHeight);
centerCanvas();
}
function draw() {
fill(0, 255, 255, random(255));
const x = windowHeight / 2 +
sin(frameCount * 0.01) * cos(frameCount * 0.04) * windowHeight / 3;
const y = windowHeight / 2 +
cos(frameCount * 0.01) * sin(frameCount * 0.04) * windowHeight / 3;
translate(x, y);
rotate(a * 0.08);
textSize(50);
textAlign(CENTER, CENTER);
text('*', 0, 0);
a += 1;
}
<script src="https://cdn.jsdelivr.net/npm/p5#1.4.1/lib/p5.js"></script>
How about this?
var a = 0;
var x = 0;
var y = 0;
var delta = 1;
function setup() {
createCanvas(windowWidth, windowHeight);
background(0, 0, 255);
}
function draw() {
fill(0, 255, 255, random(255));
x = x + 2 + Math.random();
y = y + 0.5 + Math.random();
x = x * delta;
y = y * delta;
if (x < 0) delta = -1;
translate((x) % windowWidth,(y) % windowHeight);
rotate(a);
textSize(120);
textAlign(CENTER, CENTER);
text('*', 0, 0);
rotate(a);
a = a + 0.08;
}
<script src="https://cdn.jsdelivr.net/npm/p5#1.4.1/lib/p5.js"></script>

How to work with multiple datasets in p5.js?

I want to create multiple line graphs with their own datasets into one p5.js sketch.
I created one line graph and do not know how to make another line graph to work with a different dataset.
https://editor.p5js.org/ariel.koh/sketches/VsRk3KxYp
I tried to create another preload table for my second graph but it did not work so I am still confused.
This was what I tried but I think it is not right, I never tried working with multiple datasets before so I am confused :(
let burnsdataset;
let canonattacksdataset;
function preload() {
// burns dataset
burnsdataset = loadTable("burns.csv", "csv", "header");
// canonattacks dataset
canonaattacksdataset = loadTable("canonattacks.csv", "csv",
"header");
}
You're on the right track loading the data.
The p5.js code you posted is a bit convoluted, here only a few examples:
the year labels a manually drawn, for each chart (even though the data is contained in the csv files)
if the text is simply drawn for the years but separate style, coordinate transformations, etc. are used then the push()/pop() call don't add anything.(e.g push();let sbm = 'Saul Bass Movies';...)
the drawLineGraph() function is defined twice (which might get you into variable shadowing bugs) and might be accidentally called within itself
No wonder you're confused.
I'd simplify as much as possible:
get back to loading and displaying one graph
load the second dataset (as you already correctly do above)
display the second graph
For example:
// file -> duplicate and file -> save
// this sketch first before you
// start working on it.
//
//
//
// Graph from Data, Line graph example
//
// Slides:
// http://slides.com/sojamo/cid-3-2122/fullscreen#/12/5
let burnsdataset;
let canonattacksdataset;
function preload() {
// burns dataset
burnsdataset = loadTable("burns.csv", "csv", "header");
canonaattacksdataset = loadTable("canonattacks.csv", "csv", "header");
}
function setup() {
// if you add SVG as 3rd parameter and then
// press s, the canvas will be saved as SVG file
createCanvas(displayWidth, displayHeight, SVG);
}
function draw() {
background(184, 37, 0);
//bottom label title
push();
textSize(14);
textFont("inconsolata");
textStyle(BOLDITALIC);
fill(243, 230, 214);
text("Burns", 30, 20, 330, 150); // Text wraps within text box
pop();
//linegraph
drawLineGraph({
dataset: burnsdataset,
column: 1,
x: 30,
y: 50,
w: width - 1500,
h: height - 900,
lc: color(255, 255, 255),
dc: color(169, 247, 111),
thickness: 1.5,
isCurve: true,
isDots: true,
isBackground: true,
isLabel: true,
});
//bottom label title
push();
textSize(14);
textFont("inconsolata");
textStyle(BOLDITALIC);
fill(243, 230, 214);
text("Canon Attacks", 30, 250, 330, 150); // Text wraps within text box
pop();
//linegraph
drawLineGraph({
dataset: canonaattacksdataset,
column: 1,
x: 30,
y: 280,
w: width - 1500,
h: height - 900,
lc: color(255, 255, 255),
dc: color(169, 247, 111),
thickness: 1.5,
isCurve: true,
isDots: true,
isBackground: true,
isLabel: true,
});
}
function drawLineGraph(theProps = {}) {
let values = theProps.dataset.getColumn(theProps.column);
let minValue = min(values);
let maxValue = max(values);
let x = theProps.x || 0;
let y = theProps.y || 0;
let w = theProps.w || 400;
let h = theProps.h || 300;
let bg = theProps.bg || color(255, 40);
let fg = theProps.fg || color(255, 120);
let dc = theProps.dc || color(0, 120);
let bc = theProps.bc || color(0, 120);
let lc = theProps.lc || color(255);
let thickness = theProps.thickness || 1;
let isLabel = theProps.isLabel || false;
let isCurve = theProps.isCurve || false;
let isDots = theProps.isDots || false;
let isBackground = theProps.isBackground || false;
let spacing = w / (values.length - 1);
let marginTopBottom = 20;
// we will calcualte the x and y values for each
// point first, because we need it later a couple
// of times.
let xx = [];
let yy = [];
let n = values.length;
for (let i = 0; i < n; i++) {
xx[i] = i * spacing;
yy[i] = map(
values[i],
minValue,
maxValue,
-marginTopBottom,
marginTopBottom - h
);
}
push();
translate(x, y);
translate(0, h);
// 1. draw background
if (isBackground == true) {
fill(bg);
rect(0, 0, w, -h);
// 2. draw grid
noStroke();
for (let i = 0; i < n - 1; i++) {
// fill(255,i%2 == 0 ? 80:40);
rect(xx[i], 0, 1, -h);
}
}
// 3. draw curved line graph
noFill();
stroke(lc);
strokeWeight(thickness);
beginShape();
if (isCurve == true) {
vertex(xx[0], yy[0]);
}
for (let i = 0; i < n; i++) {
let fn = isCurve == true ? curveVertex : vertex;
fn(xx[i], yy[i]);
}
if (isCurve == true) {
vertex(xx[n - 1], yy[n - 1]);
}
endShape();
// 4. draw dot / label for each value
noStroke();
// finally lets draw the dots and
// labels if enabled
let d = thickness + 8;
for (let i = 0; i < n; i++) {
push();
translate(xx[i], yy[i]);
if(isDots == true) {
fill(bc);
ellipse(0, 0, d + 4, d + 4);
fill(dc);
ellipse(0, 0, d, d);
}
if (isLabel == true) {
fill(lc)
rotate(-0.5);
textSize(7);
text(values[i], d, -d);
}
pop();
}
pop();
}
With that working you can focus on making the code nicer.
Taking the idea of "don't repeat yourself(DRY)" you can notice a few patterns that could be improved:
you try to not just draw the graph, but also also display the graph's
label: perhaps the drawLineGraph() could include that
you seem to manually be drawing every single year label, even though the data is already in the dataset and the x position is already calculated to display the points of the graph
Tackling point 1 is fairly straight foward: simply move the label drawing instrunctions inside the function, handle the extra argument to get the label text and adjust coordinates so they're relative to the graph.
Here's a modified version of the above integrating label as part of the drawLineGraph() function:
// file -> duplicate and file -> save
// this sketch first before you
// start working on it.
//
//
//
// Graph from Data, Line graph example
//
// Slides:
// http://slides.com/sojamo/cid-3-2122/fullscreen#/12/5
let burnsdataset;
let canonattacksdataset;
function preload() {
// burns dataset
burnsdataset = loadTable("burns.csv", "csv", "header");
canonaattacksdataset = loadTable("canonattacks.csv", "csv", "header");
}
function setup() {
// if you add SVG as 3rd parameter and then
// press s, the canvas will be saved as SVG file
createCanvas(displayWidth, displayHeight, SVG);
}
function draw() {
background(184, 37, 0);
//linegraph
drawLineGraph({
dataset: burnsdataset,
label: "Burns",
column: 1,
x: 30,
y: 50,
w: width - 1500,
h: height - 900,
lc: color(255, 255, 255),
dc: color(169, 247, 111),
thickness: 1.5,
isCurve: true,
isDots: true,
isBackground: true,
isLabel: true,
});
//linegraph
drawLineGraph({
dataset: canonaattacksdataset,
label: "Canon Attacks",
column: 1,
x: 30,
y: 280,
w: width - 1500,
h: height - 900,
lc: color(255, 255, 255),
dc: color(169, 247, 111),
thickness: 1.5,
isCurve: true,
isDots: true,
isBackground: true,
isLabel: true,
});
}
function drawLineGraph(theProps = {}) {
let values = theProps.dataset.getColumn(theProps.column);
let minValue = min(values);
let maxValue = max(values);
let x = theProps.x || 0;
let y = theProps.y || 0;
let w = theProps.w || 400;
let h = theProps.h || 300;
let bg = theProps.bg || color(255, 40);
let fg = theProps.fg || color(255, 120);
let dc = theProps.dc || color(0, 120);
let bc = theProps.bc || color(0, 120);
let lc = theProps.lc || color(255);
let thickness = theProps.thickness || 1;
let isLabel = theProps.isLabel || false;
let isCurve = theProps.isCurve || false;
let isDots = theProps.isDots || false;
let isBackground = theProps.isBackground || false;
let label = theProps.label || "";
let spacing = w / (values.length - 1);
let marginTopBottom = 20;
//bottom label title
push();
textSize(14);
textFont("inconsolata");
textStyle(BOLDITALIC);
fill(243, 230, 214);
text(label, x, y + h + marginTopBottom * 0.5, w, h); // Text wraps within text box
pop();
// we will calculate the x and y values for each
// point first, because we need it later a couple
// of times.
let xx = [];
let yy = [];
let n = values.length;
for (let i = 0; i < n; i++) {
xx[i] = i * spacing;
yy[i] = map(
values[i],
minValue,
maxValue,
-marginTopBottom,
marginTopBottom - h
);
}
push();
translate(x, y);
translate(0, h);
// 1. draw background
if (isBackground == true) {
fill(bg);
rect(0, 0, w, -h);
// 2. draw grid
noStroke();
for (let i = 0; i < n - 1; i++) {
// fill(255,i%2 == 0 ? 80:40);
rect(xx[i], 0, 1, -h);
}
}
// 3. draw curved line graph
noFill();
stroke(lc);
strokeWeight(thickness);
beginShape();
if (isCurve == true) {
vertex(xx[0], yy[0]);
}
for (let i = 0; i < n; i++) {
let fn = isCurve == true ? curveVertex : vertex;
fn(xx[i], yy[i]);
}
if (isCurve == true) {
vertex(xx[n - 1], yy[n - 1]);
}
endShape();
// 4. draw dot / label for each value
noStroke();
// finally lets draw the dots and
// labels if enabled
let d = thickness + 8;
for (let i = 0; i < n; i++) {
push();
translate(xx[i], yy[i]);
if(isDots == true) {
fill(bc);
ellipse(0, 0, d + 4, d + 4);
fill(dc);
ellipse(0, 0, d, d);
}
if (isLabel == true) {
fill(lc)
rotate(-0.5);
textSize(7);
text(values[i], d, -d);
}
pop();
}
pop();
}
And here's a modified version of the above that renders the labels on the x axis (year):
// file -> duplicate and file -> save
// this sketch first before you
// start working on it.
//
//
//
// Graph from Data, Line graph example
//
// Slides:
// http://slides.com/sojamo/cid-3-2122/fullscreen#/12/5
let burnsdataset;
let canonattacksdataset;
function preload() {
// burns dataset
burnsdataset = loadTable("burns.csv", "csv", "header");
// canon attacks dataset
canonaattacksdataset = loadTable("canonattacks.csv", "csv", "header");
}
function setup() {
// if you add SVG as 3rd parameter and then
// press s, the canvas will be saved as SVG file
createCanvas(displayWidth, displayHeight, SVG);
drawPlots();
}
function drawPlots() {
background(184, 37, 0);
// burnsdataset linegraph
drawLineGraph({
dataset: burnsdataset,
label: "Burns",
xColumn: 0,
yColumn: 1,
x: 30,
y: 50,
w: width - 1500,
h: height - 900,
lc: color(255, 255, 255),
dc: color(169, 247, 111),
thickness: 1.5,
isCurve: true,
isDots: true,
isBackground: true,
isLabel: true,
});
// canonaattacksdataset linegraph
drawLineGraph({
dataset: canonaattacksdataset,
label: "Canon Attacks",
xColumn: 0,
yColumn: 1,
x: 30,
y: 300,
w: width - 1500,
h: height - 900,
lc: color(255, 255, 255),
dc: color(169, 247, 111),
thickness: 1.5,
isCurve: true,
isDots: true,
isBackground: true,
isLabel: true,
});
}
function drawLineGraph(theProps = {}) {
let values = theProps.dataset.getColumn(theProps.yColumn);
let minValue = min(values);
let maxValue = max(values);
let labels = theProps.dataset.getColumn(theProps.xColumn);
let x = theProps.x || 0;
let y = theProps.y || 0;
let w = theProps.w || 400;
let h = theProps.h || 300;
let bg = theProps.bg || color(255, 40);
let fg = theProps.fg || color(255, 120);
let dc = theProps.dc || color(0, 120);
let bc = theProps.bc || color(0, 120);
let lc = theProps.lc || color(255);
let thickness = theProps.thickness || 1;
let isLabel = theProps.isLabel || false;
let isCurve = theProps.isCurve || false;
let isDots = theProps.isDots || false;
let isBackground = theProps.isBackground || false;
let label = theProps.label || "";
let spacing = w / (values.length - 1);
let marginTopBottom = 20;
// y position for labels (e.g. years)
let labelsY = marginTopBottom * 0.5;
//bottom label title
push();
textSize(14);
textFont("inconsolata");
textStyle(BOLDITALIC);
fill(243, 230, 214);
text(label, x, y - marginTopBottom, w, h); // Text wraps within text box
pop();
// we will calculate the x and y values for each
// point first, because we need it later a couple
// of times.
let xx = [];
let yy = [];
let n = values.length;
for (let i = 0; i < n; i++) {
xx[i] = i * spacing;
yy[i] = map(
values[i],
minValue,
maxValue,
-marginTopBottom,
marginTopBottom - h
);
}
push();
translate(x, y);
translate(0, h);
// 1. draw background
if (isBackground == true) {
fill(bg);
rect(0, 0, w, -h);
// 2. draw grid
noStroke();
for (let i = 0; i < n - 1; i++) {
// fill(255,i%2 == 0 ? 80:40);
rect(xx[i], 0, 1, -h);
}
}
// 3. draw curved line graph
noFill();
stroke(lc);
strokeWeight(thickness);
beginShape();
if (isCurve == true) {
vertex(xx[0], yy[0]);
}
for (let i = 0; i < n; i++) {
let fn = isCurve == true ? curveVertex : vertex;
fn(xx[i], yy[i]);
// label per data point
push();
noStroke();
fill(255);
textSize(9);
textAlign(CENTER);
text(labels[i], xx[i], labelsY);
pop();
}
if (isCurve == true) {
vertex(xx[n - 1], yy[n - 1]);
}
endShape();
// 4. draw dot / label for each value
noStroke();
// finally lets draw the dots and
// labels if enabled
let d = thickness + 8;
for (let i = 0; i < n; i++) {
push();
translate(xx[i], yy[i]);
if(isDots == true) {
fill(bc);
ellipse(0, 0, d + 4, d + 4);
fill(dc);
ellipse(0, 0, d, d);
}
if (isLabel == true) {
fill(lc)
rotate(-0.5);
textSize(7);
text(values[i], d, -d);
}
pop();
}
pop();
}
// if you want to use the SVG export
// option, go to setup and enable SVG mode
function keyPressed() {
if (key === "s") {
saveSVG("line-graph.svg");
}
}
There's one slight detail snuck in there: I've renamed draw() to drawPlots() and called it once from setup(). That is to render the plots a single time since they don't change and save CPU resources. If you do plan to have some sort interation changing these graphs then you should use draw().

p5.js change object colour after X frames

I would like to change the fill colour of an object over time. Is there a way to change the fill colour of an object after X frames?
I am learning about constructors, and I am thinking that in the code's updateParticle function, after this.age counts to 'X', the fill colour of the ellipse could change.
'''
function Particle(x, y, xSpeed, ySpeed, size, colour) {
this.x = x;
this.y = y;
this.xSpeed = xSpeed;
this.ySpeed = ySpeed;
this.size = size;
this.colour = colour;
this.age = 0;
this.drawParticle = function() {
fill(this.colour);
noStroke();
ellipse(this.x, this.y, this.size);
}
this.updateParticle = function() {
this.x += this.xSpeed;
this.y += this.ySpeed;
this.age++;
}
}
function Emitter(x, y, xSpeed, ySpeed, size, colour) {
this.x = x;
this.y = y;
this.xSpeed = xSpeed;
this.ySpeed = ySpeed;
this.size = size;
this.colour = colour;
this.particles = [];
this.startParticles = [];
this.lifetime = 0;
this.addParticle = function() {
var p = new Particle(random(this.x - 10, this.x + 10),
random(this.y - 10, this.y + 10),
random(this.xSpeed - 0.4, this.xSpeed + 0.4),
random(this.ySpeed - 5, this.ySpeed - 1),
random(this.size - 4, this.size + 40),
this.colour);
return p;
}
this.startEmitter = function(startParticles, lifetime) {
this.startParticles = startParticles;
this.lifetime = lifetime;
for (var i = 0; i < startParticles; i++) {
this.particles.push(this.addParticle());
}
}
this.updateParticles = function() {
var deadParticles = 0
for (var i = this.particles.length - 1; i >= 0; i--) {
this.particles[i].drawParticle();
this.particles[i].updateParticle();
if (this.particles[i].age > random(0, this.lifetime)) {
this.particles.splice(i, 1);
deadParticles++;
}
}
if (deadParticles > 0) {
for (var i = 0; i < deadParticles; i++) {
this.particles.push(this.addParticle());
}
}
}
}
var emit;
function setup() {
createCanvas(800, 600);
emit = new Emitter(width / 2, height - 100, 0, -1, 10, color(200, 0, 200, 50));
emit.startEmitter(600, 4000);
}
function draw() {
background(200);
emit.updateParticles();
}
'''
Well you could just:
if(frameCount % 30 == 0){ // % 30 is the remainder of num / 30, so 4 % 3 = 1, since 3 / 3 = 0 And 4 / 3 = 3.33
fill("lime") // these are just preset colors in p5.js AND css lime == rgb(0,255,0)
} else {
fill('darkred')
}
or you could also do it with for example a switch statement: using background for no reason
switch(MY_frameCount){
case 1:
background('blue')
break
case 2:
background("darkgreen")
break
case 376:
background(crimson)
// break
}
MY_frameCount ++
or:
if(Math.random() < 0.1){
fill(Math.random() * 255, Math.random() * 255, Math.random() * 255)
} // this should on average fill with random color every 10 frames

error: Type '[Assembly-UnityScript] extra field

I have this script here and for some reason I get this error.
Type '[Assembly-UnityScript]PlayerGUI' has an extra field
'healthFallRate' of type 'System.Int32' in the player and thus can't
be serialized (expected 'healthBarDisplay' of type 'System.Single')
UnityEditor.BuildPlayerWindow:BuildPlayerAndRun()
#pragma strict
//Size of Textures
var size : Vector2 = new Vector2(240, 40);
var sizeXP1 : Vector2 = new Vector2(40, 20);
var sizeXP2 : Vector2 = new Vector2(100, 20);
//Health Variables
var healthPos : Vector2 = new Vector2(20, 20);
var healthFallRate : int = 150;
var healthBarDisplay : float = 1;
var healthBarEmpty : Texture2D;
var healthBarFull : Texture2D;
//Hunger Variables
var hungerPos : Vector2 = new Vector2(20, 60);
var hungerFallRate : int = 150;
var hungerBarDisplay : float = 1;
var hungerBarEmpty : Texture2D;
var hungerBarFull : Texture2D;
//Thirst Variables
var thirstPos : Vector2 = new Vector2(20, 100);
var thirstFallRate : int = 100;
var thirstBarDisplay : float = 1;
var thirstBarEmpty : Texture2D;
var thirstBarFull : Texture2D;
//Stamina Variables
var staminaPos : Vector2 = new Vector2(20, 140);
var staminaFallRate : int = 35;
var staminaBarDisplay : float = 1;
var staminaBarEmpty : Texture2D;
var staminaBarFull : Texture2D;
//Level Up System
var currentXPPos : Vector2 = new Vector2(20, 180);
var currentXP : int = 0;
var maxXP : int = 50;
var level : int = 1;
private var leveledUp : boolean = true;
var timeToShowLevelUp : float = 3f;
var timeTillNotShowLevelUp : float = 0f;
private var chMotor : CharacterMotor;
private var controller : CharacterController;
var canJump : boolean = false;
var jumpTimer : float = 0.7;
var beginningSound : AudioClip;
private var deathMenu : DeathMenu;
function Start () {
chMotor = GetComponent(CharacterMotor);
controller = GetComponent(CharacterController);
deathMenu = GameObject.Find("First Person Controller").GetComponent(DeathMenu);
yield WaitForSeconds (5);
audio.PlayOneShot(beginningSound);
}
function OnGUI () {
//Health GUI
GUI.BeginGroup(new Rect (healthPos.x, healthPos.y, size.x, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), healthBarEmpty);
GUI.BeginGroup(new Rect (0, 0, size.x * healthBarDisplay, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), healthBarFull);
GUI.EndGroup();
GUI.EndGroup();
//Hunger GUI
GUI.BeginGroup(new Rect (hungerPos.x, hungerPos.y, size.x, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), hungerBarEmpty);
GUI.BeginGroup(new Rect (0, 0, size.x * hungerBarDisplay, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), hungerBarFull);
GUI.EndGroup();
GUI.EndGroup();
//Thirst GUI
GUI.BeginGroup(new Rect (thirstPos.x, thirstPos.y, size.x, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), thirstBarEmpty);
GUI.BeginGroup(new Rect (0, 0, size.x * thirstBarDisplay, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), thirstBarFull);
GUI.EndGroup();
GUI.EndGroup();
//Stamina GUI
GUI.BeginGroup(new Rect (staminaPos.x, staminaPos.y, size.x, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), staminaBarEmpty);
GUI.BeginGroup(new Rect (0, 0, size.x * staminaBarDisplay, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), staminaBarFull);
GUI.EndGroup();
GUI.EndGroup();
GUI.BeginGroup(new Rect (currentXPPos.x, currentXPPos.y, size.x, size.y));
GUI.Box(new Rect(0, 20, sizeXP1.x, sizeXP1.y), "XP");
GUI.Box(new Rect(0, 0, sizeXP1.x, sizeXP1.y), "Level");
GUI.Box(new Rect(40, 20, sizeXP2.x, sizeXP2.y), currentXP + "/" + maxXP);
GUI.Box(new Rect(40, 0, sizeXP2.x, sizeXP2.y), level + "");
GUI.EndGroup();
//currentXPPos
}
function Update() {
//Health Control
if(hungerBarDisplay <= 0 && (thirstBarDisplay <= 0)) {
healthBarDisplay -= Time.deltaTime / healthFallRate * 2;
}
else {
if(hungerBarDisplay <= 0 || thirstBarDisplay <= 0) {
healthBarDisplay -= Time.deltaTime / healthFallRate;
}
}
if(healthBarDisplay <= 0) {
deathMenu.enabled = true;
Debug.Log("deathMenu.enabled");
}
//Hunger Control
if(hungerBarDisplay >= 0) {
hungerBarDisplay -= Time.deltaTime / hungerFallRate;
}
if(hungerBarDisplay <= 0) {
hungerBarDisplay = 0;
}
if(hungerBarDisplay >= 1) {
hungerBarDisplay = 1;
}
//Thirst Control
if(thirstBarDisplay >= 0) {
thirstBarDisplay -= Time.deltaTime / thirstFallRate;
}
if(thirstBarDisplay <= 0) {
thirstBarDisplay = 0;
}
if(thirstBarDisplay >= 1) {
thirstBarDisplay = 1;
}
//Stamina Control
if(controller.velocity.magnitude > 0 && Input.GetKey(KeyCode.LeftShift)) {
chMotor.movement.maxForwardSpeed = 10;
chMotor.movement.maxSidewaysSpeed = 10;
staminaBarDisplay -= Time.deltaTime / staminaFallRate;
}
else {
chMotor.movement.maxForwardSpeed = 6;
chMotor.movement.maxSidewaysSpeed = 6;
staminaBarDisplay += Time.deltaTime / staminaFallRate;
}
//Jumping Section
if(Input.GetKeyDown(KeyCode.Space) && canJump == true) {
staminaBarDisplay -= 0.2;
Wait();
}
if(canJump == false) {
jumpTimer -= Time.deltaTime;
chMotor.jumping.enabled = false;
}
if(jumpTimer <= 0) {
canJump = true;
chMotor.jumping.enabled = true;
jumpTimer = 0.7;
}
if(staminaBarDisplay >= 1) {
staminaBarDisplay = 1;
}
if(staminaBarDisplay <= 0) {
staminaBarDisplay = 0;
canJump = false;
chMotor.jumping.enabled = false;
chMotor.movement.maxForwardSpeed = 6;
chMotor.movement.maxSidewaysSpeed = 6;
}
if(staminaBarDisplay < 0.2) {
canJump = false;
chMotor.jumping.enabled = false;
}
if(currentXP >= maxXP) {
LevelUpSystem();
}
if(leveledUp) {
if(Time.time > timeTillNotShowLevelUp) {
leveledUp = false;
}
}
}
function Wait() {
yield WaitForSeconds(0.1);
canJump = false;
}
function LevelUpSystem() {
currentXP = 0;
maxXP = maxXP + 50;
level++;
leveledUp = true;
timeTillNotShowLevelUp = Time.time + timeToShowLevelUp;
healthBarDisplay += 1;
hungerBarDisplay += 1;
thirstBarDisplay += 1;
staminaBarDisplay += 1;
}
same problem.I think you build by command line options.And you not set Buildtarget before building, Solution is to set target.like:
/Applications/Unity5_2/Unity.app/Contents/MacOS/Unity -batchmode -quit -executeMethod YOUR_BUILD_METHOD -projectPath YOUR_ROJECT_PATH -buildTarget ios
And than you fix this problem .

Resources