vendredi 10 avril 2020

After random repositioning of an element on canvas collison-detection doesn't work JS

The problem is with apple.x = Math.random(). After updating It's position I can't seem to get collison detection working.

function update(){
        player.x += player.xSpeed;
        player.y +=player.ySpeed;

    
    
    if(player.y > canvas.height  -10){
        player.ySpeed= -1;
    }
    if( player.y < 0){
        player.ySpeed = +1;
    }
    if(player.x == canvas.width-10||player.x == -1){
        console.log("whoops");
    }
    if(player.x == apple.x){
        apple.x = (Math.random()*700)
        ;
    }
}

All of the code:

window.onload = function(){animate(step);};
const canvas = document.getElementById("canv");
const ctx = canvas.getContext("2d");
const animate = window.requestAnimationFrame;
canvas.width = 700;
canvas.height = 400;
var player = new Snake(0,0,0,1);
var apple = new Apple(canvas.width/2,canvas.height/2,"white");

function step(){
    update();
    render();
    animate(step)
}
function render(){
    ctx.fillStyle = "black";    
    ctx.fillRect(0,0,canvas.width,canvas.height);
    player.render();

    apple.render(); 
}
function Apple(x,y,colour){
    this.x = x;
    this.y = y;
    this.colour = colour;
}

 function Snake(x,y,xSpeed,ySpeed) {
    this.xSpeed = xSpeed;
    this.ySpeed = ySpeed;
    this.x = x;
    this.y = y;
}
Snake.prototype.render = function() {
    ctx.fillStyle = "red";
    ctx.fillRect(this.x,this.y,10,10);
}
Apple.prototype.render = function(){
    ctx.fillStyle = this.colour;
    ctx.fillRect(this.x,this.y,10,10);
}

function update(){
        player.x += player.xSpeed;
        player.y +=player.ySpeed;

    
    
    if(player.y > canvas.height  -10){
        player.ySpeed= -1;
    }
    if( player.y < 0){
        player.ySpeed = +1;
    }
    if(player.x == canvas.width-10||player.x == -1){
        console.log("whoops");
    }
    if(player.x == apple.x){
        apple.x = (Math.random()*700)
        ;
    }
}
Snake.prototype.move = function(x,y){
    this.x += x;
    this.y +=y;
}

window.addEventListener("keydown", event =>{
    if(event.keyCode == 38){
        player.ySpeed = -5;
        player.xSpeed = 0;
    }
    if(event.keyCode== 40){
        player.xSpeed = 0;
        player.ySpeed= 5;
    }
    if(event.keyCode == 37){
        player.ySpeed = 0;
        player.xSpeed = -5;
    }
    if(event.keyCode == 39){
        player.xSpeed = +5;
        player.ySpeed = 0;
    }
} 


)



Aucun commentaire:

Enregistrer un commentaire