使用canvas和p5.js移动方块

时间:2019-02-14 19:45:04

标签: javascript html5-canvas p5.js

我正在尝试使用p5.js和HTML5的canvas元素来移动一个正方形。

我曾尝试以多种方式重新安排代码,有时当代码在某些地方时,画布并不是首先创建的。不管我尝试了多少次,我似乎都无法正常工作。

之所以使用变量“ direction”,是因为我计划根据所按的箭头键使其移动。

我的代码如下:

var snakeX = 0;
var snakeY = 0;
var snakeX2 = 20;
var snakeY2 = 20;
var direction = "right";
var alive = true;
var length = 2;

function setup() {
  createCanvas(window.innerWidth, window.innerHeight)
  frameRate(10);
}

function draw() {

  background(0);
  stroke(255);
  fill(255);
  rect(snakeX, snakeY, snakeX2, snakeY2);
}

if (direction == "up") {
  snakeY = snakeY + 10
  snakeY2 = snakeY - length
}

function move() {
  if (direction == "down") {

    snakeY = snakeY - 10
    snakeY2 = snakeY + length
  }
  
  if (direction == "right") {
    snakeX = snakeX + 10
    snakeX2 = snakeX - length
  }

  if (direction == "left") {

    snakeX = snakeX - 10
    snakeX2 = snakeX + length
  }
  
  loop()
}
<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js"></script>
</body>

我希望方块在打开页面时自动开始向右移动,但是仍然保持静止。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

如果我正确理解了您的问题,可以通过以下操作解决动画问题:

  • 在您的move()函数中将通话添加到draw()
  • (可选)将if(direction == 'up') { .. }块添加到move()

以下是您的代码段已更新,可以在操作中显示出来:

var snakeX = 0;
var snakeY = 0;
var snakeX2 = 20;
var snakeY2 = 20;
var direction = "right";
var alive = true;
var length = 2

function setup() {
  createCanvas(window.innerWidth, window.innerHeight)
  frameRate(10);
}

function draw() {

  background(0);
  stroke(255);
  fill(255);
  rect(snakeX, snakeY, snakeX2, snakeY2);
  
  /* Ensure move() is called for each draw() */
  move()
}


function move() {

  /* Move this inside the brackets of move() */
  if (direction == "up") {
    snakeY = snakeY + 10
    snakeY2 = snakeY - length
  }
  
  if (direction == "down") {

    snakeY = snakeY - 10
    snakeY2 = snakeY + length
  }
  
  if (direction == "right") {
    snakeX = snakeX + 10
    snakeX2 = snakeX - length
  }

  if (direction == "left") {

    snakeX = snakeX - 10
    snakeX2 = snakeX + length
  }
}
<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js"></script>
</body>

希望有帮助:)