无法在处理中移动形状
Unable to move a shape in processing
我正在尝试创建一个可以在地图上左右移动的可移动实体。我有一个设置实体初始位置的地图,但是一旦按下 '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);
}
您在 drawMap
内声明了 playerIsSpawned
。每次通过那里都会重置为 false
。
此外,考虑在顶层定义 keyPressed()
(与 draw
和 setup
相同,并在 draw
循环。
我正在尝试创建一个可以在地图上左右移动的可移动实体。我有一个设置实体初始位置的地图,但是一旦按下 '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);
}
您在 drawMap
内声明了 playerIsSpawned
。每次通过那里都会重置为 false
。
此外,考虑在顶层定义 keyPressed()
(与 draw
和 setup
相同,并在 draw
循环。