Exploring various ways to implement JavaScript animations for multiple traveling effects

I have a concept for an interactive bug animation. My idea involves having five bug images fly in from the side of the screen, bounce around randomly, and bounce off the edges. Each bug should have a unique starting position and direction.

To kick things off, I've set up some global variables:

var flyVar;

var flySpeed = 5;
var widthMax = 0;
var heightMax = 0;
var xPosition = 0;
var yPosition = 0;
var xDirection = "";
var yDirection = "";
var bugFly;

var count = 1;
var bug = "bug";

A function called setBugs() is responsible for determining the screen dimensions and adjusting the parameters accordingly.

I've also created a function called bugStartingPlace, which specifies the starting position and direction for each bug. While I won't go into all the details, the function assigns unique values to "bug1" through "bug5".

function bugStartingPlace(bugName) {
//Accepts string as argument and sets the starting position and starting direction of each bug. 
    if (bugName == "bug1") {
        xPosition = 0;
        yPosition = 100;
        xDirection = "right";
        yDirection = "up";
    }
}

For the animation itself, the flyBug() function is in charge. It sets the position of the bug image based on various conditions. While this function works for a single bug, the challenge lies in adapting it for five bugs.

function flyBug() { 
     if (xDirection == "right" && xPosition > (widthMax - document.getElementById("bugImage").width - flySpeed))
         xDirection = "left";
<!--More flow control statements are here-->

document.getElementById("bug1").style.left = xPosition + "px";
document.getElementById("bug1").style.top = yPosition + "px";
<!-- More statements are here that set the position of the image -->

}

So, the challenge now is getting the animation to start using the body onload() event. Since setInterval doesn't support functions with parameters, I've implemented a workaround using the count variable. This approach adds complexity, as I need to adjust both the count and bug names to utilize the functions effectively.

While the current setup works for a single bug, it lacks efficiency for managing multiple bugs. I welcome any insights or suggestions on how to improve the program logic.

Answer №1

When using setInterval, similar to setTimeout, you can include parameters in the function. However, the syntax is important:

setInterval(funcName(param1,param2...), 100);

This syntax will not work as intended. Instead, you should structure it like this:

var func = function () { funcName(param1,param2..); }

setInterval(func, 100);

To better understand this aspect of JavaScript, it is recommended to explore Douglas Crockford's explanation of functions, as he provides a clear and in-depth insight. Here is a link to a video by him

EDIT: Apologies for misinterpreting your question...

The reason it may not work as expected is due to global variables. An effective approach is to encapsulate the variables within an object, like creating a 'bug' object where its actions are methods. This ensures that each instance of 'bug' maintains its own variables without conflicts. Nested functions can also simplify this process.

Alternatively, you could pass the bug name as a parameter to functions like 'fly' and solely operate on that specific parameter within the function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue.js is encountering an issue with receiving the accurate return value from a POST function

I am facing an issue where I am unable to receive the full data that is being sent from the frontend to the backend. Here is an example of the data structure that I am sending: { _id: 64a8a8e9903039edb52ccc4c, productName: 'Vial 2ml(US) Type1&apos ...

can you explain the concept of a backing instance in react?

Although the concept of a "backing instance" is frequently mentioned in React documentation, I found it difficult to grasp its meaning. According to the React docs: In order to interact with the browser, you need a reference to a DOM node. By attaching ...

Integrating Vue.js code into Laravel's Blade templates for enhanced functionality

I'm having trouble accessing data from a Vue component function in a Laravel blade template that includes the component. When I use this code, the page just loads as a blank page. However, if I remove the @ symbol from the blade span, the autocomplete ...

Can MUI FormControl and TextField automatically validate errors and block submission?

Are MUI components FormControl and TextField responsible for error handling, such as preventing a form from being submitted if a required TextField is empty? It appears that I may need to handle this functionality myself, but I would like some clarificatio ...

Switch out the ajax data in the input field

Is there a way to update the value in a text box using Ajax? Below is my code snippet: <input type="text" id="category_name" name="category_name" value="<?php if(isset($compName)) { echo ucfirst($compName); ...

Guide on setting up a MEAN stack application to run on port 8080

I am brand new to the mean stack development environment. I'm attempting to configure my root domain name to display the app directory once I enter the command grunt, but the only way it currently works is at website.com:8080/!#/. How can I get it to ...

Unable to assign a boolean value to a data attribute using jQuery

I have a button on my page that has a special data attribute associated with it: <button id="manageEditContract" type="button" class="btn btn-default" data-is-allow-to-edit="@(Model.Contract.IsAllowToEdit)"> @(Model.Contract.IsAllowToEdit ? " ...

What would be the ideal technology stack (modules, frameworks) to use for delving into node.js and creating a successful first project that allows for learning and growth?

A year ago, I took my first small steps into the world of Node.js. Back then, I was overwhelmed by the sheer number of modules and frameworks available. Now, I am determined to dive deeper into the Node environment and kickstart a web-based project that wi ...

Tips for refreshing the direction route in google-maps-react

I have an array of coordinates, and when I add a new coordinate to the array, I want the route direction on the map to update accordingly. This is the code snippet from my googlemap.js file: /* global google */ import React, { Component } from "react ...

What is the best way to load the nested array attributes in an HTML table dynamically with AngularJS?

I attempted the following code, but I am only able to access values for cardno and cardtype. Why can't I access the others? Any suggestions? <tr ng-repeat="data in myData17.layouts"> <td ng-show="$index==1">{{data.name}}</td> &l ...

What is the best way to locate an element with the class name being an email address using jQuery?

Is it possible to locate an element with an email address as the class name, considering that the email address varies? $(document).ready(function(){ //not working getting error var email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Maintaining a consistent style input until it is modified

I'm currently dealing with this code (continuing from a previous question): input[type=submit]:focus { background-color: yellow; outline: none; } The issue I'm facing is that when I click anywhere else on the screen, the background color go ...

405 - Sorry, this method is not allowed for deletion

The issue at hand involves a Spring RESTful web service and a client. When attempting a DELETE request on the server, the following error is encountered: -> DELETE http://localhost:8080/employee/3/logout 405 (Method Not Allowed) Despite implementing th ...

preventing the propagation of another event

Is it possible to listen for a change event on a checkbox without triggering a click event on its container? <label><input type="checkbox"> Hello world</label> I need the action triggered by the checkbox's change event, but I want ...

Tips for integrating Server-Side Rendering into an already established React.js app running on Express.js

I am currently working on a React application and I am looking to add SSR using Express.js. Initially, I made a mistake by creating a repository with just a frontend folder containing the entire React app with typescript, babel, and webpack configurations ...

Disabling a button does not automatically shift the focus to the next element in the tab order

Is there a way to limit the number of times a button can be clicked using jQuery? For example, I want a button that can only be clicked three times before disabling itself automatically. test.html <div class="main"> <input class="one" type="t ...

Is it possible to define a constant enum within a TypeScript class?

I am looking for a way to statically set an enum on my TypeScript class and be able to reference it both internally and externally by exporting the class. As I am new to TypeScript, I am unsure of the correct syntax for this. Below is some pseudo-code (whi ...

Tips for providing support to a website without an internet connection

I am in the process of creating a sales platform for a grocery store that utilizes PHP/MySQL. I have come across some websites that are able to fully reload and function even without internet access. For instance, when I initially visited abc.com, everyth ...

What is the process for activating and deactivating the scroll trigger within Material UI's useScrollTrigger module?

I'm currently working on setting up a survey page with Material UI in React. My goal is to have the survey questions appear when the user scrolls over them and disappear when they scroll out of view, similar to the behavior on this page. After some r ...

Could there be an issue with my function parameters, or is there another underlying problem?

Hey there! I've been working on this function, but it doesn't seem to be running quite right. Here's the code: function chooseCols(colTag, tagName) { // Set column name var column = $('.tagChooser:eq(&apo ...