0

I am creating a game where you have to follow particles (divs) and click on them to "eat" them. The issue I am having currently is that I can't find a way to clone each div and give it a random X and Y coordinate value to position it.

Here is my code:

var x = e.pageX; var y = e.pageY; function reposition(div, x, y, randomMode) { if(randomMode == 1) { x = Math.floor(Math.random() * 990); y = Math.floor(Math.random() * 560); } $(div).animate({"left": x + "px"}, "slow"); $(div).animate({"top": y + "px"}, "slow"); } // need to find some way to duplicate the divs and move them in random directions setInterval(function() { for(var i = 1; i < 4; i++) { reposition("#grabItem", 0, 0, 1); } }, 2000); 

2 Answers 2

4
//select all grab items, and since there will be multiple particles //use a class to mark them, not an ID. This line is to capture all //particles existing in the markup, that are not dynamically added later var $particles = $('.grabItem'); //set your container that has all the particles var $container = $('body'); //every two seconds add a new particle at random location setInterval(function() { for(var i = 1; i < 4; i++) { $particles.add(CreateParticle()); MoveParticles(); } }, 2000); //creates a new particle and adds to the canvas function CreateParticle(){ return $('<div/>').addClass('grabItem').appendTo($container); } //randomly moves all the particles around function MoveParticles() { $particles.each(function() { var x = Math.floor(Math.random() * 990); var y = Math.floor(Math.random() * 560); $(div).animate({"left": x + "px"}, "slow"); $(div).animate({"top": y + "px"}, "slow"); }); } 

That will add a new particle at a random location every two seconds and move all existing particles around (including the new one). If you need an exact clone method check out jQuery's .clone() method.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I will try this. However, I am a bit confused with what you did inside CreateParticles()... What is $('<div/>') there for? BTW, I think you meant "</div>".
@klftw I did not mean </div> the code I posted is what I meant. If you send in an empty element to the jQuery constructor (like a self closing div tag) it creates a new DOM object for that element. Then you need to append it to the actual DOM via an .append() or .appendTo() or similar call.
0

There exists a Clone method in jQuery, is it what you are looking for?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.