【问题标题】:How to make my Rect avoiding another Rect (canvas)如何让我的 Rect 避开另一个 Rect(画布)
【发布时间】:2019-03-21 14:11:23
【问题描述】:

我正在用 JavaScript 做一个小游戏,但有一个问题,例如:我的方块随机移动,一个红色方块总是站立(不移动),当我的方块碰到红色方块时,它会自动找到路避开红场,但我不知道如何让我的广场找到穿过红场的路。我正在使用 canvas 方法 canvas.drawRect。

imgur.com/a/7e93Xn6,这是我的方格,我希望它自动上下移动以避免红色方格,但不知道如何制作,谢谢

【问题讨论】:

  • 这个描述很混乱......你能添加一个你想要实现的绘图/模型吗?
  • imgur.com/a/7e93Xn6,我想让我的方块自动上下移动以避免红色方块,但不知道怎么做,谢谢
  • 对不起,但这也没有帮助。我会尝试改写你的问题:你希望你的方块在红色方块上反弹......是这样吗?
  • 是的,就像那样,当汽车试图撞到你时,你会避开汽车

标签: javascript reactjs


【解决方案1】:

这实际上并不太复杂,您只需要不断检查这两个方块是否会在其中一个移动时接触。这可以使用它的屏幕位置和大小来计算。如果它们即将发生碰撞,只要向前移动仍然会进入另一个方格。 这是一个简单的例子:

var canvas = document.createElement("canvas");
canvas.width = 400;
canvas.height = 300;
document.body.appendChild(canvas);
var context = canvas.getContext("2d");
var Squares = function(xPos, yPos, wid, hei, col) {
  this.x = xPos;
  this.y = yPos;
  this.width = wid;
  this.height = hei;
  this.color = col;
  this.speed = 0;
}
var redSquare = new Squares(200, 100, 40, 40, "#ff0000");
var blueSquare = new Squares(0, 100, 40, 40, "#0000ff");
blueSquare.speed = 3;
var squares = [redSquare, blueSquare];

function loop() {

  if (blueSquare.x + blueSquare.width + blueSquare.speed > redSquare.x && blueSquare.y + blueSquare.height > redSquare.y) {
    blueSquare.x = redSquare.x - blueSquare.width;
    blueSquare.y -= blueSquare.speed;
  } else {
    blueSquare.x += blueSquare.speed;
  }
  if (blueSquare.x > canvas.width) {
    blueSquare.x = 0;
    blueSquare.y = 100;
  }
  context.clearRect(0, 0, canvas.width, canvas.height);
  for (var a = 0; a < squares.length; a++) {
    context.fillStyle = squares[a].color;
    context.fillRect(squares[a].x, squares[a].y, squares[a].width, squares[a].height);
  }
}
var interval = setInterval(loop, 20);

【讨论】:

  • 谢谢,这正是我需要的,在你回答之前我已经阅读了很多AI,救我一命
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-16
  • 1970-01-01
  • 2011-05-14
  • 2010-09-29
相关资源
最近更新 更多