frankdev Posted June 28, 2013 Share Posted June 28, 2013 In my code, below, I have a bouncing circle animation. I would like to make an array called circles and push back new circles when needed. I want every circle in the array to be represented by the variable circle, but have separate x and y values. Any ideas as to how I could do this ? window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(/* function */ callback, /* DOMElement */ element){ window.setTimeout(callback, 1000 / 60); }; })(); // example code from mr doob : http://mrdoob.com/lab/javascript/requestanimationframe/var canvas = document.getElementById("myCanvas"), c = canvas.getContext("2d"), time = 0, gravity = 0.1, dampening = 0.99, pullStrength = 0.01;var circle = { x: 50, y: 50, //(VX, VY) = Velocity Vector vx: 0, vy: 0, radius: 20};function update(){ requestAnimFrame(update); render();}function render (){ //c.clearRect(0, 0,canvas.width, canvas.height); c.fillStyle = 'rgba(255, 255, 255, 0.05)'; c.fillRect(0, 0, canvas.width, canvas.height); //Increment location by Velocity circle.x += circle.vx; circle.y += circle.vy; //Increment gravity over time -- Acceleration circle.vy+= gravity; //Slow it down circle.vy *= dampening; circle.vx *= dampening; //Bouncing //bottom if(circle.y + circle.radius > canvas.height){ circle.vy = -Math.abs(circle.vy); } //top if(circle.y - circle.radius < 0){ circle.vy = Math.abs(circle.vy); } //right if(circle.x + circle.radius > canvas.width){ circle.vx = -Math.abs(circle.vx); } //left if(circle.x - circle.radius < 0){ circle.vx = Math.abs(circle.vx); } c.fillStyle = 'black'; c.beginPath(); c.arc(circle.x,circle.y,circle.radius, 0 , 2* Math.PI); c.closePath(); c.fill();} canvas.addEventListener('mousedown', function(e){ var mouseX = (e.pageX||e.clientX||e.offsetX) - canvas.offsetLeft, mouseY = (e.pageY||e.clientY||e.offsetY) - canvas.offsetTop; var dx = mouseX - circle.x, dy = mouseY - circle.y; circle.vx += dx * pullStrength; circle.vy += dy * pullStrength;});update(); Quote Link to comment Share on other sites More sharing options...
Ezelia Posted June 28, 2013 Share Posted June 28, 2013 just make create array and put your circles on it var circles = [];//adding 10 circlesfor (var i =0; i<10; i++){ var circle = { x: 50, y: 50, vx: 0, vy: 0, radius: 20 }; circles.push(circle);}...//updating circlesfor (var i =0; i<circles.length; i++){ var circle = circles[i]; circle.x = some_new_Xvalue; circle.y = some_new_Yvalue; ....} Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.