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

羊毛袜

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

艾哈迈德

有无数种方法可以做到这一点。这里只是其中之一。使用画布绘制精灵,并根据精灵黑色区域内的 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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章