Reputation: 35
The thing that i wanna do is similiar with this video. In p5.js, I am using get() function. After use this, I will create small images (by dividing big tileset) and push them into an array. But in my code get()
returns an empty pixels array. Here is a part of my code:
tilesImages = []; // tiles array
function preload() {
let tilesImage = loadImage(TILEMAP_PATH + "tiles.png", () => {
console.log("Tiles loaded successfully"); // It logs this
}, () => {
console.log("An error occured when tiles loaded");
});
for (let i = 0; i < TILE_HORIZONTAL; i++) {
for (let j = 0; j < TILE_VERTICAL; j++) {
let x = i * TILE_SIZE + TILES_SPACE;
let y = j * TILE_SIZE + TILES_SPACE;
if (i == 0) {
x = 0;
}
if (j == 0) {
y = 0;
}
var img = tilesImage.get(x, y, TILE_SIZE, TILE_SIZE); // get tiles from tileset
tilesImages.push(img);
}
}
}
function setup() {
console.log(tilesImages[0].pixels); // returns empty
}
I tried to use this but it just draws vertical pink lines to my small image.
My tileset: https://www.kenney.nl/assets/pixel-shmup (on right)
I am using single images now but I want to know the solution of this problem. Thanks
Upvotes: 1
Views: 410
Reputation: 20162
I believe the issue here is that you are not waiting for the image to actually be loaded. The loadImage
function is asynchronous. That is, it only starts the process of loading the image, but it returns before it actually finish loading the image. So any code that comes after that will run immediately, while the loading is still in progress. You can use the callback function to run code after loading is complete. Here's a modified version of your code that should alleviate the problem:
tilesImages = []; // tiles array
function preload() {
let tilesImage = loadImage(
TILEMAP_PATH + "tiles.png",
() => {
console.log("Tiles loaded successfully"); // It logs this
// Wait until loading is complete to use tilesImage.get()
for (let i = 0; i < TILE_HORIZONTAL; i++) {
for (let j = 0; j < TILE_VERTICAL; j++) {
let x = i * TILE_SIZE + TILES_SPACE;
let y = j * TILE_SIZE + TILES_SPACE;
if (i == 0) {
x = 0;
}
if (j == 0) {
y = 0;
}
var img = tilesImage.get(x, y, TILE_SIZE, TILE_SIZE); // get tiles from tileset
tilesImages.push(img);
}
}
},
() => {
console.log("An error occured when tiles loaded");
}
);
}
Upvotes: 2