dimanche 30 avril 2017

How to add a logic statement to an object entering a moving area

I am trying to make a game. The object of the game is to move the square across the screen without hitting a raindrop falling from the roof. How do i make it so that if one of the raindrops enters the square, the square returns to the beginning of the canvas or x =0. Here is the code:

var canvas = document.getElementById('game');
var ctx = canvas.getContext('2d');

var WIDTH = 1000;
var HEIGHT = 700;
var x = 0;
var y = HEIGHT-20;
var xPos = [0];
var yPos = [0];
var speed = [1];
var rainDrops = 50;
var rectWidth = 20;
var rectHeight = 20;






for (var i = 0; i < rainDrops; i++) {
    xPos.push(Math.random()* WIDTH);
    yPos.push(0);
    speed.push(Math.random() * 5);

    }



function rainFall () {

    window.requestAnimationFrame(rainFall);
    ctx.clearRect(0, 0, WIDTH, HEIGHT);



    for (var i = 0; i <rainDrops; i++) {
    //Rain
    ctx.beginPath();
    ctx.arc(xPos[i], yPos[i], 3, 0, 2 * Math.PI);
    ctx.fillStyle = 'blue';
    ctx.fill();

    //Rain movement
    yPos[i]+=speed[i];

    //Box

        ctx.fillStyle = 'red';
        ctx.fillRect(x, y, rectWidth, rectWidth);

    if (yPos[i] > HEIGHT) {
        yPos[i]= 0;
        yPos[i]+=speed[0];
        }
    //This is the part where I need the Help!!!!!!!!!
    if (){
        x = 0;
    }

    }


};



//Move Object

function move (e) {
    if (e.keyCode === 37) {
        ctx.clearRect (0, 0, WIDTH, HEIGHT);
        x -=10;
    }
    if (e.keyCode === 39) {
        ctx.clearRect (0, 0, WIDTH, HEIGHT);
        x+=10;
    }
    canvas.width=canvas.width

}




//Lockl Screen

window.addEventListener("keydown", function(e) {
    // Lock arrow keys
    if( [37,39,].indexOf(e.keyCode) > -1) {
        e.preventDefault();
    }
}, false);


rainFall(); 
document.onkeydown = move;
window.addEventListener("load", doFirst, false);

Aucun commentaire:

Enregistrer un commentaire