在处理中无法移动形状

时间:2018-06-19 23:59:19

标签: processing p5.js

我正在尝试创建一个可在地图上左右移动的可移动实体。我有一张地图,用于设置实体的初始位置,但是一旦按下“ a”或“ d”键,角色只会稍微移动一下,然后在释放键后重置到其初始位置。我有一个布尔变量“ playerIsSpawned”,以确保角色的位置仅在该位置设置一次,但是这似乎没有解决任何问题。是什么原因造成的,我该如何解决?

var start_map = [
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 9, 0, 0, 0, 0, 0, 0],
  [1, 1, 1, 1, 1, 1, 1, 1]
];
var playerX;
var playerY;

function drawPlayer() {
  fill(0);
  rect(playerX, playerY, 50, 50);
}

function drawMap(map) {
  // The x and y do not represent the x and y axis
  // Keep in mind a 2d array is an array of an array
  noStroke();
  var playerIsSpawned = false;

  for (var x = 0; x < map.length; x++) {
    for (var y = 0; y < map.length; y++) {
      // Background
      if (map[y][x] == 0) {
        fill(184, 236, 255);
        rect((10 + 50*x), (10 + 50*y), 50, 50);
      }
      // Ground
      else if (map[y][x] == 1) {
        fill(51, 153, 51);
        rect((10 + 50*x), (10 + 50*y), 50, 50);
      }
      // Player
      else if (map[y][x] == 9) {
        if (playerIsSpawned == false) {
          playerX = (10 + 50*x);
          playerY = (10 + 50*y);
          playerIsSpawned = true;
        }
        fill(184, 236, 255);
        rect((10 + 50*x), (10 + 50*y), 50, 50);
      }
    }
  }
  drawPlayer();
  function keyPressed() {
    if (key == "d") {
      playerX += 5;
    }
    else if (key == "a") {
      playerX -= 5;
    }
  }
  keyPressed();
}

function setup() {
  background(0);
  createCanvas(800, 800);
}

function draw() {
  drawMap(start_map);
}

1 个答案:

答案 0 :(得分:1)

您在playerIsSpawned内声明了drawMap。每次通过该操作都会重置为false

另外,请考虑在顶层定义keyPressed()(与drawsetup相同,并摆脱对{{1} }循环。