简体   繁体   中英

Making divs constantly move randomly

I have created a shooting game for children, where they have to shoot the correct number (depending on the question) when it appears. My problem is at the moment the numbers appear one at a time but I would like to make it so that the canvas is constantly populated with numbers that keep moving around like the shapes in this example... http://sheppardsoftware.com/mathgames/earlymath/shapes_shoot.htm

function moveRandom(id) {

var cPos = $('#container').offset();
var cHeight = $('#container').height();
var cWidth = $('#container').width();

// get box padding (assume all padding have same value)
var pad = parseInt($('#container').css('padding-top').replace('px', ''));

// get movable box size
var bHeight = $('#' + id).height();
var bWidth = $('#' + id).width();

// set maximum position
maxY = cPos.top + cHeight - bHeight - pad;
maxX = cPos.left + cWidth - bWidth - pad;

// set minimum position
minY = cPos.top + pad;
minX = cPos.left + pad;

// set new position
newY = randomFromTo(minY, maxY);
newX = randomFromTo(minX, maxX);

$('#' + id).css({
    top: newY,
    left: newX
}).fadeIn(2000, function() {
    setTimeout(function() {
        $('#' + id).fadeOut('fast');
        window.cont++;
    }, 1500);
});

Here is the version I have created http://jsfiddle.net/pUwKb/5/

does it work if you replace the css() method with animate() ?

$('#' + id).animate({
    top: newY,
    left: newX
}).fadeIn(2000, function() {
    setTimeout(function() {
        $('#' + id).fadeOut('fast');
        window.cont++;
    }, 1500);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM