This is from a Khanacademy project - I was wondering why when I try to apply my repulsion force from my buglight to each of the flies why does it return __env__.flies[j].applyForce is not a function.
I had been messing around with this and can't get it to accept that force. Also when I try to make the glow of the buglight within that function change by adding an amount and then removing an amount it looks like it is happening too fast because it is only showing the maximum glow amount.
CODE:
// I created a light over where the mouse is and the flies (random start poisitions) are drawn toward the light, but I included some randomness to their movements to add some variation to their paths, the flies are repelled from the buglight using a repulsion force:
var Mover = function() {
this.position = new PVector (random(width),random(height));
this.velocity = new PVector (0,0);
this.acceleration = new PVector (0,0);
this.mass = 1;
};
Mover.prototype.update = function () {
var mouse = new PVector(mouseX,mouseY);
var dist = PVector.sub(mouse, this.position);
var randomPush = new PVector(random(-1,1),random(-1,1));
dist.normalize();
dist.mult(0.4);
this.acceleration = dist;
this.acceleration.add(randomPush);
this.velocity.add(this.acceleration);
this.velocity.limit(9);
this.position.add(this.velocity);
};
Mover.prototype.display = function () {
strokeWeight(7);
stroke(0, 0, 0);
point(this.position.x,this.position.y);
strokeWeight(5);
point(this.position.x - 3,this.position.y -3);
point(this.position.x + 3,this.position.y -3);
};
var Buglight = function (){
this.position = new PVector (random(width-50),random(height-80));
this.velocity = new PVector (0,0);
this.acceleration = new PVector (0,0);
this.glow = 70;
this.mass = 20;
this.G = 1;
};
Buglight.prototype.update = function() {
noStroke();
fill(39, 131, 207,90);
ellipse(this.position.x+20,this.position.y+35,this.glow,this.glow);
};
Buglight.prototype.repulsion = function(fly) {
var force = PVector.sub(this.position,fly.position);
var distance = force.mag();
distance = constrain(distance, 4.0, 20.0);
force.normalize();
var strength = -1 *(this.G * this.mass * fly.mass) / (distance * distance);
force.mult(strength);
return force;
};
Buglight.prototype.display = function() {
noStroke();
fill(5, 170, 252);
rect(this.position.x+15,this.position.y,10,60);
fill(0, 0, 0);
noStroke();
rect(this.position.x-10,this.position.y+60,60,10,10);
rect(this.position.x,this.position.y,10,60);
rect(this.position.x+30,this.position.y,10,60 );
quad(this.position.x,this.position.y,
this.position.x-10,this.position.y+20,
this.position.x+50,this.position.y+20,
this.position.x+40,this.position.y);
};
Buglight.prototype.checkEdges = function () {
};
var flies = [];
for (var i = 0; i < 4; i++){
flies[i] = new Mover();
}
var buglight = new Buglight();
var fly = new Mover();
draw = function() {
background(71, 71, 71);
strokeWeight(56);
stroke(219, 247, 8,100);
fill(255, 238, 0);
ellipse(mouseX,mouseY,20,20);
buglight.update();
buglight.display();
for (var j = 0; j < flies.length; j++) {
var blueForce = buglight.repulsion(flies[j]);
flies[j].applyForce(blueForce);
flies[j].update();
flies[j].display();
}
};
There is no applyForce function on your Mover class. Something is missing I feel.
Related
I'm trying to use a button to toggle the audio for a P5 oscillator on and off (because as I understand it, WebAudio API stuff requires an interaction in browsers now for audio to play).
Before the setup I have:
var button;
In the function setup I have:
button = createButton("audio on/off");
button.mousePressed(toggle);
button.position(32, 180);
In function toggle I have:
if (!playing()) {
osc.start();
//playing = true; } else {
osc.stop();
//playing = false; }
It keeps giving me the error message
Uncaught ReferenceError: toggle is not defined (sketch: line 45)"
Why do I keep getting this? Any help would be greatly appreciated.
The full sketch.js code is:
var button;
var stepX;
var stepY;
let osc;
function setup() {
createCanvas(displayWidth, displayHeight);
noCursor();
noStroke();
colorMode(HSB, width, height, 100);
reverb = new p5.Reverb();
delay = new p5.Delay();
osc = new p5.Oscillator();
osc.setType('sine');
reverb.process(osc, 5, 5);
osc.start();
// delay.process() accepts 4 parameters:
// source, delayTime, feedback, filter frequency
// play with these numbers!!
delay.process(osc, 0.6, 0.3, 1000);
// play the noise with an envelope,
// a series of fades ( time / value pairs )
var t = 10
let text = createP("s-p-e-c-t-r-u-m");
text.position(30, 30);
text.style("font-family", "monospace");
text.style("background-color", "#FFFFFF");
text.style("color", "#F20FD7");
text.style("font-size", "12pt");
text.style("padding", "10px");
let texty = createP("move mouse to control the <br>sine-wave theramin.<br><br>x axis = pitch 30-3000hz<br>y axis = volume quiet-loud)");
texty.position(32, 80);
//texty.style("background-color", "#FFFFFF");
texty.style("font-family", "monospace");
texty.style("color", "#FFFFFF");
texty.style("font-size", "10pt");
button = createButton("audio on/off");
button.mousePressed(toggle);
button.position(32, 180);
}
function draw() {
let pitch = map(mouseX, 0, width, 30, 3000);
let volume = map(mouseY, 0, height, 1, 0);
background(200);
osc.freq(pitch);
osc.amp(volume);
stepX = mouseX + 2;
stepY = mouseY + 2;
for (var gridY = 0; gridY < height; gridY += stepY) {
for(var gridX = 0; gridX < width; gridX += stepX) {
fill(gridX, height - gridY, 100);
rect(gridX, gridY, stepX, stepY);
}
}
function toggle() {
if (!playing) {
osc.start();
playing = true;
} else {
osc.stop();
playing = false;
}
}
}
toggle is declared in scope of draw:
function draw() {
// [...]
function toggle() {
// [...]
}
}
Move it out of draw, top solve the issue:
function draw() {
// [...]
}
function toggle() {
// [...]
}
See the example:
var button;
var stepX;
var stepY;
let osc;
function setup() {
createCanvas(displayWidth, displayHeight);
noCursor();
noStroke();
colorMode(HSB, width, height, 100);
reverb = new p5.Reverb();
delay = new p5.Delay();
osc = new p5.Oscillator();
osc.setType('sine');
reverb.process(osc, 5, 5);
osc.start();
// delay.process() accepts 4 parameters:
// source, delayTime, feedback, filter frequency
// play with these numbers!!
delay.process(osc, 0.6, 0.3, 1000);
// play the noise with an envelope,
// a series of fades ( time / value pairs )
var t = 10
let text = createP("s-p-e-c-t-r-u-m");
text.position(30, 30);
text.style("font-family", "monospace");
text.style("background-color", "#FFFFFF");
text.style("color", "#F20FD7");
text.style("font-size", "12pt");
text.style("padding", "10px");
let texty = createP("move mouse to control the <br>sine-wave theramin.<br><br>x axis = pitch 30-3000hz<br>y axis = volume quiet-loud)");
texty.position(32, 80);
//texty.style("background-color", "#FFFFFF");
texty.style("font-family", "monospace");
texty.style("color", "#FFFFFF");
texty.style("font-size", "10pt");
button = createButton("audio on/off");
button.mousePressed(toggle);
button.position(32, 180);
}
function draw() {
let pitch = map(mouseX, 0, width, 30, 3000);
let volume = map(mouseY, 0, height, 1, 0);
background(200);
osc.freq(pitch);
osc.amp(volume);
stepX = mouseX + 2;
stepY = mouseY + 2;
for (var gridY = 0; gridY < height; gridY += stepY) {
for(var gridX = 0; gridX < width; gridX += stepX) {
fill(gridX, height - gridY, 100);
rect(gridX, gridY, stepX, stepY);
}
}
}
function toggle() {
if (!playing) {
osc.start();
playing = true;
} else {
osc.stop();
playing = false;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.sound.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.dom.js"></script>
Try assigning your functions to variables. Without doing that all your functions will be hoisted to the top of the file at run time. Also make sure you declare toggle before you use it!
In my project i have 2 lines.
Each line changes position when you click on the screen.
The position of each line always falls randomly in thirds of the screen width.
I accomplished the clicks and the random position in thirds.
Now i would like the lines to animate to the new position on mousePress but i don’t know how to go about it. i’m wondering if a have to rebuild in another way.
can someone guide me? :slight_smile:
https://editor.p5js.org/antoniofrom1984/sketches/8n9le2Wvh
function setup(){
createCanvas(windowWidth, windowHeight);
}
function draw(){
noLoop();
background(backcolor);
}
function mousePressed(){
loop();
var h = height;
var w = width;
var thirdsH = [h/3, h/2, h/1.5 ];
var thirdsV = [w/3, w/2, w/1.5];
var randomthirdsH = random(thirdsH);
var randomthirdsV = random(thirdsV);
strokeWeight(2);
stroke(linecolor);
line(0, randomthirdsH, w, randomthirdsH);
line(randomthirdsV, 0 ,randomthirdsV, h);
print(randomthirdsH);
}
To do what you want you, you've to remove tha noLoop() instruction and to implement the animation in draw().
Define a current_pos variable for the current position of the line, a target_pos variable for the target position of the line and a speed for the animation. Let current_pos and target_pos undefined:
let current_pos, target_pos;
let speed = 2;
Set the target position target_pos, when the mouse is pressed:
function mousePressed(){
var h = height;
var w = width;
var thirdsH = [h/3, h/2, h/1.5 ];
var thirdsV = [w/3, w/2, w/1.5];
target_pos = [random(thirdsV), random(thirdsH)];
}
As soon as target_pos is define, start to draw the line in draw. If current_pos is not defined, then initialize current_pos by target_pos. This happens when the line is drawn the first time:
if (target_pos) {
if (!current_pos) {
current_pos = [target_pos[0], target_pos[1]];
} else {
// [...]
}
// [...]
}
When the target_pos is changed the change the current_pos by speed and slightly move it in the direction of target_pos:
for (let i = 0; i < 2; ++i) {
if (current_pos[i] < target_pos[i])
current_pos[i] = Math.min(target_pos[i], current_pos[i]+speed)
else if (current_pos[i] > target_pos[i])
current_pos[i] = Math.max(target_pos[i], current_pos[i]-speed)
}
Always draw the line at current_pos:
line(0, current_pos[1], width, current_pos[1]);
line(current_pos[0], 0, current_pos[0], height);
See the example, where I applied the suggestions to your original code:
let backcolor = (0, 0, 0);
let linecolor = (255, 255, 255);
let current_pos, target_pos;
let speed = 2;
function setup(){
createCanvas(windowWidth, windowHeight);
// this is just to see somthing at start
target_pos = [10, 10]
}
function draw(){
background(backcolor);
if (target_pos) {
if (!current_pos) {
current_pos = [target_pos[0], target_pos[1]];
} else {
for (let i = 0; i < 2; ++i) {
if (current_pos[i] < target_pos[i])
current_pos[i] = Math.min(target_pos[i], current_pos[i]+speed)
else if (current_pos[i] > target_pos[i])
current_pos[i] = Math.max(target_pos[i], current_pos[i]-speed)
}
}
// draw lines
strokeWeight(2);
stroke(linecolor);
line(0, current_pos[1], width, current_pos[1]);
line(current_pos[0], 0, current_pos[0], height);
// draw target marker
strokeWeight(3);
stroke(255, 0, 0);
line(target_pos[0]-10, target_pos[1], target_pos[0]+10, target_pos[1]);
line(target_pos[0], target_pos[1]-10, target_pos[0], target_pos[1]+10);
}
}
function mousePressed(){
var h = height;
var w = width;
var thirdsH = [h/3, h/2, h/1.5 ];
var thirdsV = [w/3, w/2, w/1.5];
target_pos = [random(thirdsV), random(thirdsH)];
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>
I assume you mean that the splitting of the canvas happens at the point where you click, something like this:
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}
var backcolor = "rgb(194, 24, 91)";
var linecolor = "rgb(240, 98, 146)";
var h;
var w;
var thirdsH;
var thirdsV;
var randomthirdsH;
var randomthirdsV;
function setup(){
createCanvas(windowWidth, windowHeight);
}
function draw(){
noLoop();
background(backcolor);
}
function mousePressed(){
loop();
var h = height;
var w = width;
var thirdsH = [h/3, h/2, h/1.5 ];
var thirdsV = [w/3, w/2, w/1.5];
var randomthirdsH = mouseY;
var randomthirdsV = mouseX;
strokeWeight(2);
stroke(linecolor);
line(0, randomthirdsH, w, randomthirdsH);
line(randomthirdsV, 0 ,randomthirdsV, h);
print(randomthirdsH);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>
The key thing here being:
var randomthirdsH = mouseY;
var randomthirdsV = mouseX;
In the mousePressed() handler.
I am having a bit of a nightmare applying different background images onto balls that bounce around in the canvas under the effect of gravity and the bounds of my canvas, eventually settling down and stacking at the bottom.
I have created an image array, that I am trying to loop through and create a ball for each image, where the image becomes a centred background.
I can centre the image, but this makes the balls appear to leave the bounds of my canvas. So have reverted that change.
I am unable to get the background image to be different from the previous ball. Where the image shown on all balls is the last image in the array. However the number of balls created does reflect the number of images in the array.
Here is a link to a codepen:
https://codepen.io/jason-is-my-name/pen/BbNRXB
html, body{
width:100%;
height:100%;
margin: 0;
padding: 0;
background: #333333;
}
*{
margin: 0;
padding: 0;
}
.container {
width: 410px;
height: 540px;
}
#ball-stage{
width: 100%;
height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<canvas id="ball-stage" ></canvas>
</div>
<script>
/*
/*
* Created by frontside.com.au
* Amended by Jason
*/
$(document).ready(function () {
$.ajaxSetup({
cache: true
});
var url1 = "https://code.createjs.com/easeljs-0.6.0.min.js";
$.getScript(url1, function () {
new App();
})
});
function App() {
var self = this;
self.running = false;
self.initialized = false;
var stageClicked = false;
var stage, canvas;
var canvasWidth = 410;
var canvasHeight = 540;
var bounce = -0.75;
var balls = [];
var _gravityY = 1;
var _gravityX = 0;
var FPS = 30;
var infoText, detailsText;
var ballsInitalized = false;
var iOS = navigator.userAgent.match(/(iPod|iPhone|iPad)/);
self.initialize = function () {
toggleListeners(true);
self.initCanvas();
self.initGame();
};
var toggleListeners = function (enable) {
if (!enable) return;
};
self.refresh = function () {}
self.initCanvas = function () {
canvas = $("#ball-stage").get(0);
stage = new createjs.Stage(canvas);
window.addEventListener('resize', onStageResize, false);
onStageResize();
createjs.Touch.enable(stage);
createjs.Ticker.addListener(tick);
createjs.Ticker.setFPS(FPS);
self.initialized = true;
}
self.initGame = function () {
initBalls(canvasWidth, canvasHeight);
}
var onStageResize = function () {
stage.canvas.width = canvasWidth;
stage.canvas.height = canvasHeight;
}
var initBalls = function (stageX, stageY) {
var imagesArray = ["img-1.png","img-2.png","img-3.png","img-4.png","img-5.png","img-6.png","img-7.png","img-8.png"];
for (var i = 0; i < imagesArray.length; i++) {
console.log(i);
var imageArray = imagesArray[i];
console.log(imageArray);
setTimeout(function () {
var arrayImage = new Image();
console.log(arrayImage);
arrayImage.onload = function(){
addBall(arrayImage, stageX / 2, 0);
}
arrayImage.src = imageArray;
}, i * 1000);
}
}
var addBall = function (img, x, y) {
console.log(img);
var shape = new createjs.Shape();
shape.id = balls.length;
shape.radius = 51.25;
shape.mass = shape.radius;
shape.x = x;
shape.y = y;
shape.vx = rand(-3, 3);
shape.vy = rand(-3, 3);
var image = new Image();
image.src = img;
shape.graphics.beginBitmapFill(img,'repeat').drawCircle(0, 0, shape.radius);
stage.addChild(shape);
balls.push(shape);
}
var numBalls = function () {
return balls.length;
}
var tick = function () {
balls.forEach(move);
for (var ballA, i = 0, len = numBalls() - 1; i < len; i++) {
ballA = balls[i];
for (var ballB, j = i + 1; j < numBalls(); j++) {
ballB = balls[j];
checkCollision(ballA, ballB);
}
}
stage.update();
}
var rotate = function (x, y, sin, cos, reverse) {
return {
x: (reverse) ? (x * cos + y * sin) : (x * cos - y * sin),
y: (reverse) ? (y * cos - x * sin) : (y * cos + x * sin)
};
}
var checkCollision = function (ball0, ball1) {
var dx = ball1.x - ball0.x,
dy = ball1.y - ball0.y,
dist = Math.sqrt(dx * dx + dy * dy);
//collision handling code here
if (dist < ball0.radius + ball1.radius) {
//calculate angle, sine, and cosine
var angle = Math.atan2(dy, dx),
sin = Math.sin(angle),
cos = Math.cos(angle),
//rotate ball0's position
pos0 = {
x: 0,
y: 0
}, //point
//rotate ball1's position
pos1 = rotate(dx, dy, sin, cos, true),
//rotate ball0's velocity
vel0 = rotate(ball0.vx, ball0.vy, sin, cos, true),
//rotate ball1's velocity
vel1 = rotate(ball1.vx, ball1.vy, sin, cos, true),
//collision reaction
vxTotal = vel0.x - vel1.x;
vel0.x = ((ball0.mass - ball1.mass) * vel0.x + 2 * ball1.mass * vel1.x) /
(ball0.mass + ball1.mass);
vel1.x = vxTotal + vel0.x;
//update position - to avoid objects becoming stuck together
var absV = Math.abs(vel0.x) + Math.abs(vel1.x),
overlap = (ball0.radius + ball1.radius) - Math.abs(pos0.x - pos1.x);
pos0.x += vel0.x / absV * overlap;
pos1.x += vel1.x / absV * overlap;
//rotate positions back
var pos0F = rotate(pos0.x, pos0.y, sin, cos, false),
pos1F = rotate(pos1.x, pos1.y, sin, cos, false);
//adjust positions to actual screen positions
// ball1.x = ball0.x + pos1F.x;
setBallX(ball1, ball0.x + pos1F.x)
//ball1.y = ball0.y + pos1F.y;
setBallY(ball1, ball0.y + pos1F.y)
// ball0.x = ball0.x + pos0F.x;
setBallX(ball0, ball0.x + pos0F.x)
// ball0.y = ball0.y + pos0F.y;
setBallY(ball0, ball0.y + pos0F.y)
//rotate velocities back
var vel0F = rotate(vel0.x, vel0.y, sin, cos, false),
vel1F = rotate(vel1.x, vel1.y, sin, cos, false);
ball0.vx = vel0F.x;
ball0.vy = vel0F.y;
ball1.vx = vel1F.x;
ball1.vy = vel1F.y;
}
}
var checkWalls = function (ball) {
if (ball.x + ball.radius > canvas.width) {
// ball.x = canvas.width - ball.radius;
setBallX(ball, canvas.width - ball.radius)
ball.vx *= bounce;
} else
if (ball.x - ball.radius < 0) {
// ball.x = ball.radius;
setBallX(ball, ball.radius)
ball.vx *= bounce;
}
if (ball.y + ball.radius > canvas.height) {
// ball.y = canvas.height - ball.radius;
setBallY(ball, canvas.height - ball.radius)
ball.vy *= bounce;
} else
if (ball.y - ball.radius < 0) {
//ball.y = ball.radius;
setBallY(ball, ball.radius)
ball.vy *= bounce;
}
}
var move = function (ball) {
ball.vy += _gravityY;
ball.vx += _gravityX;
setBallX(ball, ball.x + ball.vx)
setBallY(ball, ball.y + ball.vy)
checkWalls(ball);
}
var setBallX = function (ball, x) {
if (isNaN(ball.pointerID)) {
ball.x = x
}
}
var setBallY = function (ball, y) {
if (isNaN(ball.pointerID)) {
ball.y = y
}
}
var rand = function (min, max) {
return Math.random() * (max - min) + min;
return (Math.random() * max) + min;
}
self.initialize();
return self;
}
window.log = function f() {
log.history = log.history || [];
log.history.push(arguments);
if (this.console) {
var args = arguments,
newarr;
args.callee = args.callee.caller;
newarr = [].slice.call(args);
if (typeof console.log === 'object') log.apply.call(console.log, console, newarr);
else console.log.apply(console, newarr);
}
};
(function (a) {
function b() {}
for (var c = "assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","), d; !!(d = c.pop());) {
a[d] = a[d] || b;
}
})
(function () {
try {
console.log();
return window.console;
} catch (a) {
return (window.console = {});
}
}());
</script>
I have been trapped at this point in the code for about a week now and could really do with some genius' help!
Aims:
Add balls equivalent to the length of the image array.
Each ball with have its respective image as a centred background.
The balls will not leave the bounds of the canvas.
Relevant code:
initBalls()
addBall()
Thanks, Jason.
https://codepen.io/prtjohanson/pen/vPKQBg
What needed to be changed:
for (let i = 0; i < imagesArray.length; i++) {
console.log(i);
const imageArray = imagesArray[i];
setTimeout(function() {
var arrayImage = new Image();
arrayImage.onload = function() {
addBall(arrayImage, stageX / 2, 0);
};
arrayImage.src = imageArray;
}, i * 1000);
}
By the time the setTimeout callback fired, your for loop had already finished and with a var declaration, the for loop iteration has no scope of its own, with a let, each iteration has its own scope like a function does.
If it must run on browsers that don't have let or const keywords, let me know, I can provide a solution for them as well
This will work in IE11 and other browsers that don't support ES6
for (var i = 0; i < imagesArray.length; i++) {
(function(imageArray) {
setTimeout(function() {
var arrayImage = new Image();
arrayImage.onload = function() {
console.log('Add'+i);
addBall(arrayImage, stageX / 2, 0);
};
arrayImage.src = imageArray;
}, i * 1000);
})(imagesArray[i]);
}
To get the images centered, without them going out of the bounds of canvas, use a 2D transform on the beginBitmapFill operation:
var transform = new createjs.Matrix2D();
transform.appendTransform(-shape.radius, -shape.radius, 1, 1, 0);
shape.graphics.beginBitmapFill(img, "repeat", transform).drawCircle(0, 0, shape.radius);
As for there being not as many balls as there are URLs in the array, it seems that sometimes the image source URL prompts "I am not a robot" captcha. If replaced with URL-s under your control, the issue should go away.
I'm trying to use p5.js's p5.collide2D library to execute some actions. I have a main pulsing module that pulses size-wise to music playing in my sketch, and then as it hits certain shapes I have displaying, I want it to reference the different functions I've set up to transform the main module visually.
Currently in this sketch I'm trying to get the Circle2 function to draw when touchX + touchY collides with the maroon circle. I thought I was using the library correctly, but maybe not. Any help would be great. Thanks!
var circles = [];
var squares = [];
var sizeProportion = 0.2;
//additional shapes
var r = 0;
var velocity = 1;
var fillColor = color(0, 0, 0);
var hit = false;
var startTime;
var waitTime = 3000;
var drawCircles;
var drawSquares;
function preload() {
sound = loadSound('assets/findingnemoegg.mp3');
}
function setup() {
createCanvas(windowWidth, windowHeight);
amplitude = new p5.Amplitude();
sound.loop();
sound.play();
startTime = millis();
}
function draw() {
background(255);
// other shapes + information
r = r + velocity;
if ((r > 256) || (r < 0)) {
velocity = velocity * -1;
}
noStroke();
fill(144, 12, 63, r);
ellipse(100, 100, 80, 80);
// drawing circles
circles.push(new Circle1(touchX, touchY));
for (var i = 0; i < circles.length; i++) {
circles[i].display();
if (circles[i].strokeOpacity <= 0) { // Remove if faded out.
circles.splice(i, 1); // remove
}
}
//collisions
if (pointTouchcircle2(touchX, 100, 100)) { // <- collision detection
//call upon Circle2 function and have the main module draw that
} else {
//stay the same.
}
}
//starting circles
function Circle1(x, y) {
this.x = x;
this.y = y;
this.size = 0;
this.age = 0;
this.fillOpacity = 20
this.strokeOpacity = 30
this.display = function() {
var level = amplitude.getLevel();
this.age++;
if (this.age > 500) {
this.fillOpacity -= 1;
this.strokeOpacity -= 1;
}
var newSize = map(level, 0, 1, 20, 900);
this.size = this.size + (sizeProportion * (newSize - this.size));
strokeWeight(10);
stroke(152, 251, 152, this.strokeOpacity);
fill(23, 236, 236, this.fillOpacity);
ellipse(this.x, this.y, this.size);
}
}
//maroon circles
function Circle2(x, y) {
this.x = x;
this.y = y;
this.size = 0;
this.age = 0;
this.fillOpacity = 20
this.strokeOpacity = 30
this.display = function() {
var level = amplitude.getLevel();
this.age++;
if (this.age > 500) {
this.fillOpacity -= 1;
this.strokeOpacity -= 1;
}
var newSize = map(level, 0, 1, 20, 900);
this.size = this.size + (sizeProportion * (newSize - this.size));
strokeWeight(10);
stroke(173, 212, 92, this.strokeOpacity);
fill(144, 12, 63, this.fillOpacity);
ellipse(this.x, this.y, this.size);
}
}
//collision functions
function pointTouchcircle2(touch, x, y) {
if (hit = collidePointCircle(touchX,touchY,100,100,50)) {
return true
} else {
return false
}
}
Goal
The stripes in the background remain fixed while the cones rotate about the center.
Current State
live demo:
https://codepen.io/WallyNally/pen/yamGYB
/*
The loop function is around line 79.
Uncomment it to start the animation.
*/
var c = document.getElementById('canv');
var ctx = c.getContext('2d');
var W = c.width = window.innerWidth;
var H = c.height = window.innerHeight;
var Line = function() {
this.ctx = ctx;
this.startX = 0;
this.startY = 0;
this.endX = 0;
this.endY = 0;
this.direction = 0;
this.color = 'blue';
this.draw = function() {
this.ctx.beginPath();
this.ctx.lineWidth = .1;
this.ctx.strokeStlye = this.color;
this.ctx.moveTo(this.startX, this.startY);
this.ctx.lineTo(this.endX, this.endY);
this.ctx.closePath();
this.ctx.stroke();
}
this.update = function() {
//for fun
if (this.direction == 1) {
this.ctx.translate(W/2, H/2);
this.ctx.rotate(-Math.PI/(180));
}
}//this.update()
}//Line();
objects=[];
function initLines() {
for (var i =0; i < 200; i++) {
var line = new Line();
line.direction = (i % 2);
if (line.direction == 0) {
line.startX = 0;
line.startY = -H + i * H/100;
line.endX = W + line.startX;
line.endY = H + line.startY;
}
if (line.direction == 1) {
line.startX = 0;
line.startY = H - i * H/100;
line.endX = W - line.startX;
line.endY = H - line.startY;
}
objects.push(line);
line.draw();
}
}
initLines();
function render(c) {
c.clearRect(0, 0, W, H);
for (var i = 0; i < objects.length; i++)
{
objects[i].update();
objects[i].draw();
}
}
function loop() {
render(ctx);
window.requestAnimationFrame(loop);
}
//loop();
What I have tried
The translate(W/2, H/2) should place the context at the center of the page, then this.ctx.rotate(-Math.PI/(180)) should rotate it one degree at a time. This is the part that is not working.
Using save()and restore() is the proper way to keep some parts of an animation static while others move. I placed the save and restore in different parts of the code to no avail. There are one of two types of result : Either a new entirely static image is produced, or some erratic animation happens (in the same vein of where it is now).
Here is the changed pen: http://codepen.io/samcarlinone/pen/LRwqNg
You needed a couple of changes:
var c = document.getElementById('canv');
var ctx = c.getContext('2d');
var W = c.width = window.innerWidth;
var H = c.height = window.innerHeight;
var angle = 0;
var Line = function() {
this.ctx = ctx;
this.startX = 0;
this.startY = 0;
this.endX = 0;
this.endY = 0;
this.direction = 0;
this.color = 'blue';
this.draw = function() {
this.ctx.beginPath();
this.ctx.lineWidth = .1;
this.ctx.strokeStlye = this.color;
this.ctx.moveTo(this.startX, this.startY);
this.ctx.lineTo(this.endX, this.endY);
this.ctx.closePath();
this.ctx.stroke();
}
this.update = function() {
//for fun
if (this.direction == 1) {
this.ctx.translate(W/2, H/2);
this.ctx.rotate(angle);
this.ctx.translate(-W/2, -H/2);
}
}//this.update()
}//Line();
objects=[];
function initLines() {
for (var i =0; i < 200; i++) {
var line = new Line();
line.direction = (i % 2);
if (line.direction == 0) {
line.startX = 0;
line.startY = -H + i * H/100;
line.endX = W + line.startX;
line.endY = H + line.startY;
}
if (line.direction == 1) {
line.startX = 0;
line.startY = H - i * H/100;
line.endX = W - line.startX;
line.endY = H - line.startY;
}
objects.push(line);
line.draw();
}
}
initLines();
function render(c) {
c.clearRect(0, 0, W, H);
for (var i = 0; i < objects.length; i++)
{
ctx.save();
objects[i].update();
objects[i].draw();
ctx.restore();
}
}
function loop() {
render(ctx);
window.requestAnimationFrame(loop);
angle += Math.PI/360;
}
loop();
First I added a variable to keep track of rotation and increment it in the loop
Second I save and restore for each individual line, alternatively if all lines were going to perform the same transformation you could move that code before and after the drawing loop
Third to get the desired affect I translate so the center point is in the middle of the screen, then I rotate so that the lines are rotated, then I translate back because all the lines have coordinates on the interval [0, H]. Instead of translating back before drawing another option would be to use coordinates on the interval [-(H/2), (H/2)] etc.