Как остановить игру при определённом условии(Canvas JS)

Создал что-то вроде игры, теперь задача которую не пойму как реализовать: если шарик коснётся хоть одного прямоугольника, то нужно остановить игру

по нажатию на пробел можно контролировать высоту шарика

вот мой код:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas width="600" height="600" style="background: black;"></canvas>
    
    <script>
    class Canvas{
    constructor(){
        this.canvas=document.querySelector('canvas')
        this.ctx=this.canvas.getContext('2d')
    }
}
//===============================================
 class Ball extends Canvas{
    constructor(){
        super();
        this.x=50
        this.y=250
        this.r=15
        this.road=true;
    }
    
    paint(){
        this.ctx.beginPath()
        this.ctx.arc(this.x,this.y,this.r,0,6.28)
        this.ctx.fillStyle='red'
        this.ctx.fill()
        this.ctx.closePath()
    }
    move(){
        this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)
         if(this.road){
             this.y+=20
         }else{
             this.y-=40
             this.road=true
         }
         if(this.y>=this.canvas.height){
             this.y=this.canvas.height-20
         } 
         this.paint()
    }
 }
 //============================================
 class Game{
    constructor(){
        this.shar=new Ball()
        this.pugl= new Grid()
        document.body.addEventListener('keydown',(e)=>{
            if(e.key==' '){
                this.shar.road=false
            }
        })
    }
    play(){
        setInterval(()=>{
            this.shar.paint()
            this.shar.move()
            this.pugl.paint()
            this.pugl.move()
           },200)
    }
}
 //=========================================
 class Grid extends Canvas{
    constructor(){
        super();

        this.setka=[];

        for(let i=0;i<12;i++){
            let obj= new Pugl()
            obj.x=300+80*i
            obj.h=parseInt(Math.random()*250)
            if(i%2==0){
                obj.y=this.canvas.height-obj.h
            }
             
            this.setka.push(obj)
         }
    }

    paint(){
        this.setka.map(item=>item.paint() )
    }

    move(){
        this.setka.map(item=>{
            item.x-=80;
             if(item.x<=0){
                item.x+=750; 
              }
          })

        this.paint()
    }
}
 
class Pugl extends Canvas{
    constructor(){
        super();
        this.x=300
        this.y=0
        this.w=20
        this.h=100
    }
    paint(){
        this.ctx.fillRect(this.x,this.y,this.w,this.h)
        this.ctx.fillStyle='white'
     }
 }
  
      let app=new Game()
      app.play()
     </script>
</body>
</html>

Я не гуру, но когда-то смотрел видео как делали flappy bird и там механика та же по идее, при соприкосновении с трубами игра завершается. Вбей в ютубе

1 лайк

ок, спвсибо

Что значит “коснется”? Это значит что координаты объектов пересекутся. Гугли hitbox и 2d coordinates collision.
Что значит остановить игру - значит не выполнять следующий вызов функции в интервале (в индустрии называют game loop).

Ответ на твой вопрос - на каждой итерации игрового цикла считай коллизии объектов и если они произошли, то останавливай игровой цикл.