jQuery spawning div and collision detection

前端 未结 2 1185
攒了一身酷
攒了一身酷 2021-01-29 10:03

So im almost at the end of my school homework project im just missing two major things i can\'t seem to figure out:

1.How to spawn the pipe obstacles with a random posit

2条回答
  •  情话喂你
    2021-01-29 10:30

    first of all i've changed your CSS little bit to arrange the code and set the different width groups classes ('.zero', '.one', etc.) for the pipes, you can add more width groups or edit it later but notice the ratio between the pipes sides width and the bird width.

    #bird
    {
        position:absolute;
        width:4%;
        height: auto;
        right:0;
    }
    
    #fullPipe
    {
        position:absolute;
        width:100%;
        left:0%;
        height: 10%;
    }
    
    #leftPipe, #rightPipe
    {
        position:absolute;
        top:0;
        width:48%;
        height: 100%;
    }
    
    #leftPipe
    {
        left:0%;
    }
    
    #rightPipe
    {
        right:0%;
    }
    
    .zero #leftPipe, .zero #rightPipe
    {
        width:48%;
    }
    
    .one #leftPipe
    {
        width:8%;
    }
    
    .one #rightPipe
    {
        width:88%;
    }
    
    .two #leftPipe
    {
        width:28%;
    }
    
    .two #rightPipe
    {
        width:68%;
    }
    
    .three #leftPipe
    {
        width:58%;
    }
    
    .three #rightPipe
    {
        width:38%;
    }
    
    .four #leftPipe
    {
        width:88%;
    }
    
    .four #rightPipe
    {
        width:8%;
    }
    
    #leftPipe img, #rightPipe img
    {
        width:100%;
        height: 100%;
    }
    

    in The JS, notice the condition inside the setInterval(), i set it for now to '700' for the demo but after you will set the collision ready, you can replace it with condition of if the pipes and the body not in collision (out of the frame) then reset the pipes and set new width group class.

        var PipesRandom;
        var PipesWidth = ['zero', 'one', 'two', 'three', 'four'];  
        function spawnPipe(astY){ //spawn asteroids
            $('#fullPipe').css("top", astY);  
        }  
        setInterval(function(){
            astY += 1;
            if(astY < 700){
                spawnPipe(astY);
            } 
            else {
                astY = -100;
                PipesRandom = PipesWidth[Math.floor(Math.random() * PipesWidth.length)];
                $('#fullPipe').removeClass('zero one two three four');
                $('#fullPipe').addClass(PipesRandom);
                spawnPipe(astY);
            }
        } ,10);
    

    example: http://jsfiddle.net/u38ratk9/8/

    about the collision, there are a lot of options, you can check this question for example: Please recommend a JQuery plugin that handles collision detection for draggable elements

    or: Basic 2d collision detection

    there are a lot, just search.

提交回复
热议问题