内部间隔内的js间隔不起作用

时间:2015-06-01 18:50:13

标签: javascript meteor intervals 2d-games

我正在尝试构建游戏 - 目标是只收集从浏览器顶部掉落的正确对象。

我创建了一个间隔,它调用一个每隔5秒创建一个新元素的函数,在该函数内部我创建了另一个间隔,检查元素是否到达底部。

问题是 - 当创建其他元素时(5秒后),检查器间隔停止检查当前元素并开始检查新元素 - 因此它永远不会到达底部。

这是代码:

    var newDrop =function(){
    random = Math.random();
    randNum = Math.floor(foodsImages.length * Math.random());
    drop = $('<img class="drop" src="'+ foodsImages[randNum].img +'">').appendTo('.board');
    drop.css({ top:0 - drop.height(), left: random * ($(window).width() - drop.width())});
    drop.animate({
        top: $('.board').height()
    }, 15000, function(){
        $(this).remove()
    });
    checkStop = setInterval(function(){new basket(drop, foodsImages[randNum])} , 30);
    drop.attr('interval', checkStop);
};

var basket = function(elm,obj){
    console.log(elm.offset().top + elm.height() > $('.basket').offset().top);
    if (elm.offset().top + elm.height() > $('.basket').offset().top){ //reached to the end
        leftLarger = elm.offset().left <= $('.basket').offset().left; 
        rightSmaller = elm.offset().left + elm.width() >= $('.basket').offset().left + $('.basket').width();

        if ( leftLarger && rightSmaller) { //if its been catched

            if (obj.value == true) { //and its a good thing
                console.log("yyah");
            }else{ // if its a bad thing
                console.log("bozzz");
            };

        }else{ //wasnt cathced

            if (obj.value == true) { //and suposed to cach
                console.log("bozzz");
            }else{
                console.log("msg");             
            };
        };

        elm.remove();
        return clearInterval( elm.checkStop ); //stop tracking
    };
}

$(function(){
    //handle drag movment
    $('.board').height( $(window).height() - $('header').height() );
    $('.basket').draggable({ 
        axis: "x",
        containment: "parent",
        scroll: false
    });

    //handle keypress on computers
    $(document).on("keydown", function (e) {
        var currentpost = $('.basket').offset().left;
        switch(e.which) {
            case 39:
                if ( (currentpost + $('.basket').width() ) < $(window).width()){
                    $('.basket').css('left', currentpost + 10);
                }
                break;
            case 37:
                if (currentpost - 10 > 0 ){
                    $('.basket').css('left', currentpost - 10);
                }
                break;
            default:
                return false;
        }
    });

    //objects
    foodsImages = [
        {
            "name": "adashim",
            "img" : "http://www.bulbsort.com/puzzlingapples/img/icon256x256.png",
            "value": true
        },
        {
            "name": "adom",
            "img" : "http://vignette1.wikia.nocookie.net/clubpenguin/images/8/86/Tacos_Puffle_Food.png/revision/latest?cb=20130820230847",
            "value": false
        },
        {
            "name": "tavshil",
            "img" : "https://tonytimecp.files.wordpress.com/2011/12/coin.png",
            "value": true
        },
        {
            "name": "pasta",
            "img" : "http://upload.wikimedia.org/wikipedia/commons/1/19/Food_Barnstar_Hires.png",
            "value": false
        }
    ];

    newDrop();
    addDrop = setInterval( function(){ newDrop() } , 5000);
});

这是演示:DirectX SDK Tools Catalog

1 个答案:

答案 0 :(得分:0)

我创造了一个新的小提琴https://jsfiddle.net/qkjounLb/

您需要了解如何正确使用关键字new和this。有了这个理解OO,范围和闭包是有帮助的。虽然不是必需的,但在这种情况下,了解范围以及如何操作范围可以快速解决问题。我不知道你的游戏程序的其他部分的范围,所以可能已经过度使用这个关键字,但说明了这一点。

您可以从https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures开始,但有很多文章可以通过搜索来了解JavaScript中的范围。

var betterDrop = function(foodsImages){
    this.random = Math.random();
    this.randNum = Math.floor(foodsImages.length * Math.random());

    this.drop = $('<img class="drop" src="'+ foodsImages[this.randNum].img +'">').appendTo('.board');
    this.drop.css({ top:0 - this.drop.height(), left: this.random * ($(window).width() - this.drop.width())});
    this.drop.animate({
        top: $('.board').height()
    }, 15000, function(){
        $(this).remove()
    });

    var scope = this;

    this.checkStop = setInterval(function(){new basket(scope.drop, foodsImages[scope.randNum])} , 30);
    this.drop.attr('interval', scope.checkStop);
}

var basket = function(elm,obj){
    console.log(elm.offset().top + elm.height() > $('.basket').offset().top);
    if (elm.offset().top + elm.height() > $('.basket').offset().top){ //reached to the end
        leftLarger = elm.offset().left <= $('.basket').offset().left; 
        rightSmaller = elm.offset().left + elm.width() >= $('.basket').offset().left + $('.basket').width();

        if ( leftLarger && rightSmaller) { //if its been catched

            if (obj.value == true) { //and its a good thing
                console.log("yyah");
            }else{ // if its a bad thing
                console.log("bozzz");
            };

        }else{ //wasnt cathced

            if (obj.value == true) { //and suposed to cach
                console.log("bozzz");
            }else{
                console.log("msg");             
            };
        };

        elm.remove();
        return clearInterval( elm.checkStop ); //stop tracking
    };
}

$(function(){
    //handle drag movment
    $('.board').height( $(window).height() - $('header').height() );
    $('.basket').draggable({ 
        axis: "x",
        containment: "parent",
        scroll: false
    });

    //handle keypress on computers
    $(document).on("keydown", function (e) {
        var currentpost = $('.basket').offset().left;
        switch(e.which) {
            case 39:
                if ( (currentpost + $('.basket').width() ) < $(window).width()){
                    $('.basket').css('left', currentpost + 10);
                }
                break;
            case 37:
                if (currentpost - 10 > 0 ){
                    $('.basket').css('left', currentpost - 10);
                }
                break;
            default:
                return false;
        }
    });

    //objects
    foodsImages = [
        {
            "name": "adashim",
            "img" : "http://www.bulbsort.com/puzzlingapples/img/icon256x256.png",
            "value": true
        },
        {
            "name": "adom",
            "img" : "http://vignette1.wikia.nocookie.net/clubpenguin/images/8/86/Tacos_Puffle_Food.png/revision/latest?cb=20130820230847",
            "value": false
        },
        {
            "name": "tavshil",
            "img" : "https://tonytimecp.files.wordpress.com/2011/12/coin.png",
            "value": true
        },
        {
            "name": "pasta",
            "img" : "http://upload.wikimedia.org/wikipedia/commons/1/19/Food_Barnstar_Hires.png",
            "value": false
        }
    ];

    new betterDrop(foodsImages);


addDrop = setInterval( function(){ new betterDrop(foodsImages) } , 5000);
});