2016-07-08 8 views
0

Я создаю javascript игру, где мне нужно столкнуться между мячом и прямоугольником, чтобы вызвать перезагрузку игры. На данный момент у меня просто есть предупреждение для тестирования. У меня возникли проблемы с работой обнаружения столкновений.Обнаружение столкновений между кругом и прямоугольником в игре Javascript?

Это то, что у меня до сих пор, но он не работает

  function startGame() { 
      keeper = new obstacle(40, 20, "#666", 130, 180); 
      theBall = new component("#000", 80, 10); 
      myGameArea.start(); 
     } 

     var myGameArea = { 
      canvas : document.createElement("canvas"), 
      start : function() { 
       this.canvas.width = 300; 
       this.canvas.height = 250; 
       this.context = this.canvas.getContext("2d"); 
       document.body.insertBefore(this.canvas, document.body.childNodes[0]); 
       this.interval = setInterval(updateGameArea, 20); 
       window.addEventListener('keydown', function(e) { 
        myGameArea.key = e.keyCode; 
       }) 
       window.addEventListener('keyup', function(e) { 
        myGameArea.key = false; 
       }) 
      }, 
      clear : function() { 
       this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); 
      } 
     } 

     function component(color, x, y, type) { 

      this.type = type; 
      this.speed = 1.5; 
      this.angle = 0; 
      this.x = x; 
      this.y = y; 
      this.update = function() { 
       ctx = myGameArea.context; 
       ctx.save(); 
       ctx.translate(this.x, this.y); 
       ctx.rotate(this.angle); 
       ctx.beginPath(); 
       ctx.arc(this.x, this.y, 10, 0, 2 * Math.PI); 
       ctx.fillStyle = color; 
       ctx.fill(); 
       ctx.restore(); 
      } 
      this.newPos = function() { 
       this.x -= this.speed * Math.sin(this.angle); 
       this.y += this.speed * Math.cos(this.angle); 
      } 
     } 

     function obstacle(width, height, color, x, y) { 
      this.width = width; 
      this.height = height; 
      this.speedX = 0; 
      this.speedY = 0; 
      this.x = x; 
      this.y = y; 
      this.update = function() { 
       ctx = myGameArea.context; 
       ctx.fillStyle = color; 
       ctx.fillRect(this.x, this.y, this.width, this.height); 
      } 
      this.newPos = function() { 
       this.x += this.speedX; 
       this.y += this.speedY; 
      } 
     this.collideWith = function(theBall){ 
     var collide = true; 
     var myTop =this.y; 
     var theBallBottom = theBall.y + (theBall.radius) 
     if (myTop < theBallBottom) 
     { 
     collide = false; 
     } 
     return collide; 
     } 
     } 

     function updateGameArea() { 
     if (keeper.crashWith(theBall)) { 
       alert("Collision"); 
      } else { 
       myGameArea.clear(); 
       theBall.newPos(); 
       theBall.update(); 
     keeper.speedX = 0; 
     keeper.speedY = 0; 
      if (myGameArea.key && myGameArea.key == 37) {keeper.speedX = -1; } 
      if (myGameArea.key && myGameArea.key == 39) {keeper.speedX = 1; } 
     keeper.newPos(); 
     keeper.update(); 
     } 
     } 

В игре можно найти здесь http://alexhollingsworth.co.uk/game.php

+0

Вы смотрите на это сообщение [http://stackoverflow.com/questions/21089959/detecting-collision-of-rectangle-with-circle](http://stackoverflow.com/questions/21089959/detecting- столкновения из-прямоугольника с кругом)? –

ответ

0

Вы назвали ваш метод collideWith, но вы вызываете его crashWith в метод обновления. Плюс это только обнаружит столкновение по оси y, но я предполагаю, что это предназначено.

0

я сделал, если заявление, которое может обнаружить столкновения в JavaScript, здесь:

if circle x < rect x + circle width && circle x + rect width > rect x && circle y < rect y + circle height && rect height + circle y > rect y { 

Это работает, положив мяч в «воображаемом поле», то чувствует, если какой-либо из краев " воображаемая коробка "вступает в контакт с любым из краев прямоугольника. Надеюсь, это помогло.