Elements: Random appear

Hi! I would like to ask if there is a java script function that functions as a randomizer.
I’m thinking of creating a game where there are many choices that will appear on screen but I want them to move and appear randomly.

Here’s the code that I have initially but it’s not working

function randomizer(doc, e) {
const gameElements = [
{ name: “opt1a”, correct: true },
{ name: “opt1b”, correct: true },
{ name: “opt1c”, correct: true },
{ name: “opt2a”, correct: false },
{ name: “opt2b”, correct: false },
{ name: “opt2c”, correct: false },
];

function shuffle(array) {
for (let i = array.length - 1; i > 0; i–) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}

function generateGameElements() {
const gameContainer = doc.getElement(“background”);
gameElements.forEach((element, index) => {
const elementDiv = doc.createElement(“div”);
elementDiv.innerHTML = element.name;
elementDiv.style.position = “absolute”;
elementDiv.style.left = ${index * 100}px;
elementDiv.style.top = ${Math.random() * 200}px;
elementDiv.addEventListener(“click”, () => {
if (element.correct) {
alert(“Correct!”);
} else {
alert(“Incorrect!”);
}
});
gameContainer.appendChild(elementDiv);
});
}

function moveGameElements() {
const gameContainer = doc.getElement(“background”);
gameContainer.childNodes.forEach((element, index) => {
let left = parseFloat(element.style.left) || 0;
left += index + 1;
element.style.left = ${left}px;
if (left > gameContainer.offsetWidth) {
element.style.left = “-100px”;
}
});

}

Hi Leon,

It’s a nice idea to make that kind of game with Saola Animate.
But if you do not have much coding experience, I suggest that you can manually create elements moving and appearing in the editor.
Just add elements to the Canvas then freely create motion paths in any shape you want.
Kindly take a look at this article for details: Create Motion Paths in Saola Animate 3 - Atomi Systems, Inc.

Best regards,
Thuy

Hi, Thank you for the response. I actually did it in the editor in the mean time. Is there a way to make them appear randomly every time the game resets?

Thank you!

Yes, it is possible to do that with JavaScript. Kindly take a look at the sample below for details:
random-position.saolapack (4.9 KB)
In this sample, both the Scene Activate event and the Reset button’s On Click event run the same code to seek Timeline.

That’s why when the scene is activated or when the Reset button is clicked, the elements will appear randomly.

Hope that it addresses your concern.
Thuy

1 Like

This is really helpful! Thank you so much!