繁体   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