JavaScript 具有多个按钮的游戏对象

JavaScript game object with multiple buttons

我需要创建一个由多个按钮组成的游戏对象,或者创建一个会对点击精灵不同部分做出不同反应的精灵。我正在使用 Phaser 框架。我有一个非常简单的精灵代表一个芯片,有两个小输入,一个主体(矩形)和一个小输出。我想让游戏根据点击的部分做不同的事情。为每个项目创建不同的按钮和精灵并以某种方式将它们组合在一起的最佳做法是什么?或者我可以使用一个精灵,并以某种方式为每个部分定义不同的功能吗?

有无数种方法可以做到这一点。这里只是其中之一。 使用canvas绘制精灵,并根据精灵黑色区域内的x,y位置检测点击事件的位置。

var canvas = document.getElementById('game_canvas');

var cnvLeft = canvas.offsetLeft,
  cnvTop = canvas.offsetTop;
var chip = {
  x: 20,
  y: 20,
  width: 90,
  height: 40
};


var ctx = canvas.getContext('2d');

ctx.fillRect(chip.x, chip.y, chip.width, chip.height);


canvas.addEventListener('click', function(event) {
  var x = event.pageX - cnvLeft,
    y = event.pageY - cnvTop;
  if (x > chip.x && x < chip.x + chip.width / 2 && y > chip.y && y < chip.y + chip.height) {
    ctx.fillStyle = "gold";
    ctx.fillRect(chip.x, chip.y, chip.width / 2, chip.height);
    console.log('You clicked my left side');
  } else if (x > chip.width / 2 && x < chip.x + chip.width && y > chip.y && y < chip.y + chip.height) {
    ctx.fillStyle = "cyan";
    ctx.fillRect(chip.x + chip.width / 2, chip.y, chip.width / 2, chip.height);
    console.log('You clicked my right side');
  }
})
<h3>Click the black area</h3>

<canvas id="game_canvas" width="300" height="200"></canvas>