簡體   English   中英

使用Javascript,畫布和Alpha檢測進行碰撞檢測

[英]Collision Detection with Javascript, Canvas, and Alpha Detection

我目前正在開發一個基本的Javascript游戲,該游戲具有兩個不會碰撞在一起的精靈。 但是,基本的邊界框碰撞是不夠的,因為精靈的某些部分是透明的,不會“算作”碰撞。 我找到了解決我遇到的問題的方法,但無法使其正常工作。 我想做的是計算精靈的透明部分,並確保如果透明部分重疊,則不會檢測到碰撞。 這是我發現的解決問題的方法。

http://blog.weeblog.net/?p=40#comments

  /**
   * Requires the size of the collision rectangle [width, height]
   * and the position within the respective source images [srcx, srcy]
   * 
   * Returns true if two overlapping pixels have non-zero alpha channel
   * values (i.e. there are two vissible overlapping pixels)
   */
  function pixelCheck(spriteA, spriteB, srcxA, srcyA, srcxB, srcyB, width, height){
    var dataA = spriteA.getImageData();
    var dataB = spriteB.getImageData();

    for(var x=0; x<width; x++){
      for(var y=0; y<height; y++){
        if( (dataA[srcxA+x][srcyA+y] > 0) && (dataB[srcxB+x][srcyB+y] > 0) ){
          return true;
        }
      }
    }
    return false;
  }

並計算圖像數據:

    /**
     * creating a temporary canvas to retrieve the alpha channel pixel
     * information of the provided image
     */
    function createImageData(image){
      $('binaryCanvas').appendTo('body');
      var canvas = document.getElementById('binaryCanvas');
      var ctx      = canvas.getContext("2d");

      ctx.drawImage(image, 0, 0);
      var canvasData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      var imageData  = [image.width];

      for(var x=0; x<image.width; x++){
        imageData[x] = [image.height];
        for(var y=0; y<image.height; y++){
          var idx = (x + y * image.width) * 4;
          imageData[x][y] = canvasData.data[idx+3];
        }
      }
      $("#binaryCanvas").remove();
      return imageData;
    }

問題是我不知道如何實現此解決方案,或者這是否是解決我的問題的最佳解決方案。 這是我要找的東西嗎? 如果是這樣,我應該將這些方法放在哪里? 我最困惑的是應該傳遞給spriteA和spriteB。 我嘗試傳遞圖像,並嘗試傳遞從pixelCheck方法返回的imageData,但是收到相同的錯誤:對象或圖像has no method 'getImageData' 我究竟做錯了什么?

這有兩件事是錯誤的。

您做了一個功能:

function createImageData(image){...}

但是您所說的是:

spriteA.getImageData();
spriteB.getImageData();

點表示對象的屬性。 您試圖調用一個從來都不屬於對象的函數。 有一些簡單的修復程序。

將createImageData()函數添加到構造函數中:

function Sprite(){
    ...
    this.createImageData = function(image){...};
    ...
}

要么 :

Sprite.createImageData = function(image{...};

或正確地調用它:

createImageData(spriteA.image); // or whatever the image is

其次,您的函數需要一個圖像參數,但是您沒有提供一個。 只需記住在調用時提供圖像即可。 您也可以刪除參數並從函數中獲取圖像。

有點像這樣:

function Sprite(){
    ...
    this.createImageData = function(){
        var image = this.image;
        // or just use this.image, or whatever it is
        ...
    }
    ...
}

希望這會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM