How do I…
I have a script that should generate objects in a grid. The object type is “Sprite”, the name is “Sprocket”, and the layer to be generated on is “Sprockets”. I have three arrays, one for the X coordinates, one for the Y coordinates, and one for the angle of the sprocket. Each sprocket should be generated at a random angle picked from the angles array.
What is the expected result
When the game loads, the sprockets should generate in a grid, with each facing a random angle.
What is the actual result
I’m getting this error:
Uncaught exception: TypeError: Cannot read properties of undefined (reading ‘length’)
I’m pretty sure it’s from the following line, but I’m a novice JS programmer, so I’m not sure how to fix it.
const randomAngleIndex = Math.floor(Math.random() * angle.length);
Code
(function (runtimeScene, objects /*Sprocket*/) {
if (runtimeScene.getTimeManager().isFirstFrame()) {
// The sprockets' X coordinates
const X = [
28, 58, 88, 118, 148, 178, 208, 238, 268, 298, 328, 358, 388, 418, 448,
478, 508, 538, 568, 598, 628, 658,
];
// The sprockets' Y coordinates
const Y = [
128, 158, 188, 218, 248, 278, 308, 338, 368, 398, 428, 458, 488, 518,
548, 578, 608, 638, 668, 698, 728, 758, 788, 818, 848, 878, 908, 938,
968, 998, 1028, 1058, 1088, 1118, 1148, 1178, 1208,
];
// The sprockets' angles in degrees
const angle = [0, 90, 180, 270];
// Set the object type
const objectType = 'Sprite';
// Set the object layer
const layer = runtimeScene.getLayer('Sprockets');
// Iterate through each coordinate in the X and Y arrays
for (let i = 0; i < X.length; i++) {
for (let j = 0; j < Y.length; j++) {
// Get a random angle from the angle array
const randomAngleIndex = Math.floor(Math.random() * angle.length);
const randomAngle = angle[randomAngleIndex];
// Create a Sprocket at the current coordinates with the random angle
const sprite = new gdjs.RuntimeObject(runtimeScene, objectType);
sprite.setX(X[i]);
sprite.setY(Y[j]);
sprite.setAngle(randomAngle);
// Set the layer of the Sprite object
sprite.setLayer(layer);
// Add the Sprite object to the scene
runtimeScene.addObject(sprite);
}
}
}
})(runtimeScene, objects /*Sprocket*/);
Thanks.