Is it time to refresh the value of the variable's random number?

Is there a way to update a variable with a random number in three.js? I'm facing an issue where the sprite generated at a random location seems to keep reverting back to the same spot after the initial call. Despite my attempts to update the variables, the problem persists. Here's the snippet of code I'm working with:

        var locX = Math.floor((Math.random()*450)+1);
        locX *= Math.floor(Math.random()*2) == 1 ? 1 : -1;
        var locY = Math.floor((Math.random()*250)+1);
        locY *= Math.floor(Math.random()*2) == 1 ? 1 : -1;
        var locZ = Math.floor((Math.random()*350)+1);
        locZ *= Math.floor(Math.random()*2) == 1 ? 1 : -1;          

        function spriteAI1() {
        //console.log(c2Sprite.position.x);
        //console.log(ranLocX);
        //console.log(ranTen);
            if (c2Sprite.position.x > 30 && c2Sprite.position.x <= 450) { 
            c2Sprite.translateX( -10 );
            } else if (c2Sprite.position.x < -31 && c2Sprite.position.x >= -450) {
            c2Sprite.translateX( 10 );
            } else if (c2Sprite.position.z < 31 && c2Sprite.position.x < 31 && c2Sprite.position.z > -29 && c2Sprite.position.x > -29) { 
            locX;
            locY;
            locZ;
            //c2Sprite.delete;
            //scene.remove(c2Sprite);
            //console.log("AI1");
            c2Sprite.position.set( locX, locY, locZ );
            //scene.add( c2Sprite );
            //c2Sprite.clone;
            }
        }   

Answer №1

To ensure distinct values with each call, make sure to declare the variables inside the function rather than outside of it. By currently having them set externally, the function will continuously reference those initial values regardless of how many times it's called.

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

How can I include a nested object in an ng-repeat loop in Angular?

I'm new to using Angular so please excuse my basic question. Here is the structure of my model for posts and comments: [ { "title": "awesome post", "desc": "asdf", "comment_set": [ { "id": 2, ...

What factors outside of the program could potentially lead to the splice function not functioning as expected?

Within my code, I encountered a peculiar issue involving a splice line along with debug lines on both sides. Take a look: const obj = { x:[1,2], y:{t:"!!!"} } const lenBefore = S.groupings.length const ret = S.groupings.splice(gix, 0, obj) console.log(`${ ...

A pop-up modal that remains closed thanks to sessionStorage

I've been working on creating a modal that pops up after a short delay, but once closed, it shouldn't appear again unless the user closes the website and starts a new session. While I have successfully designed the modal, integrating sessionStora ...

Is it acceptable to use JavaScript to code positioning if the standard HTML flow is not behaving as expected?

After contemplating for a long time, I have finally mustered the courage to ask this question. The behavior of HTML elements in normal flow has always bewildered me. Controlling them can be quite challenging, especially when dealing with server-side coding ...

What is the best way to remove the class "active" from only one of the <li> elements using jQuery?

I am currently facing a challenge in figuring out how to remove the "active" class from just one of my lists. Here is an example of my navigation bar: <div class="container"> <ul class="nav"> <li class="active"><a href="#">& ...

Getting the length of child elements in Angular using ngFor loop

Can anyone help me figure out how to check the length of a child element in my Angular *ngFor loop? I am fetching data from a real-time firebase database. What am I doing wrong? Here is the code snippet I am using: <div *ngFor="let event of events"> ...

Attempting to grasp the concept of Promises in Angular 2

I have encountered an issue while working with the Google API service and I am stuck at the promise response stage. Here is the code snippet for reference: getPromise: Promise<any>; loadSheets: Array<any>; constructor(public _checkAuthApiServ ...

Switching the background image when hovering over a list element

Looking at the screenshot, it's clear that there is an unordered list with a background image set on the div. What I am trying to achieve is to have the background image change whenever I hover over a list item. Each list item should trigger a differe ...

Tips for effectively implementing a curried selector function with the useSelector hook in react-redux

In my project using react-redux with hooks, I encountered a situation where I needed a selector that takes a parameter which is not passed as a prop. Upon checking the documentation, it mentioned: The selector function does not receive an ownProps argum ...

Implementing the 'keepAlive' feature in Axios with NodeJS

I've scoured through numerous sources of documentation, Stack Overflow threads, and various blog posts but I'm still unable to make the 'keepAlive' functionality work. What could I be overlooking? Here's my server setup: import ex ...

Resolving the Angular5 (Angular Universal) problem with page source visibility

Currently tackling a server-side rendering project, inspired by the Angular Universal guide. Everything seems to be on track, but I'm facing an issue where even when navigating to different routes, the source code for the initial page is displayed whe ...

What is the best way to structure files within the css and js folders after running the build command in Vue-cli?

Vue-cli typically generates files in the following structure: - dist -- demo.html -- style.css -- file.commom.js -- file.commom.js.map -- file.umd.js -- file.umd.js.map -- file.umd.min.js -- file.umd.min.js.map However, I prefer to organize them this way: ...

Sorting functionality malfunctioning after dynamically adding new content using AJAX

Greetings to all, I have a question about my views. 1- Index 2- Edit In the index view, I have a button and AJAX functionality. When I click the button, it passes an ID to the controller which returns a view that I then append to a div. The Edit view con ...

Using Node, Express, and Swig Template to incorporate variables within HTML attributes

I have been utilizing as the template engine for my Node/Express application. Although I am able to pass data into the template successfully, I am encountering difficulties when trying to use variables. My code snippet looks like this: {% for person in ...

What is the best way to download a file with a specific name using Angular and TypeScript?

Greetings! Below is a snippet of code from my Angular component: this.messageHistoryService.getMessageHistoriesCSV1(msgHistoryRequest).subscribe( (data) => { console.log(data.messageHistoryBytes); let file = new Blob( [data.messageHistoryBytes ...

Connect guarantees while generating template

Fetching data through a function. Establishing a connection and retrieving necessary information. Some code has been omitted for brevity. function executeSQL(sql, bindParams , options) { return new Promise(function(resolve, reject) { ... resolv ...

Dealing with an endless loop caused by a promise in AngularJS's ui router $stateChangeStart event

I am currently working on implementing authentication in my Angular application and I want to redirect to an external URL when a user is not logged in (based on a $http.get request). However, I seem to be stuck in an infinite loop when using event.prevent ...

What is the process for configuring a headless implementation of three.js on a node server, similar to the babylon.js-NulEngine setup?

My current project involves the development of a multiplayer three.js fps game, with client-side prediction in the browser. For the server-side implementation, I am utilizing Node.js Express.js and Socket.io for handling authoritative functions such as col ...

AngularJS fails to trigger window scroll event

Although I have come across similar inquiries regarding this issue, none of the solutions have proven to be effective for me. Currently, I am working with AngularJS and I am attempting to detect the scroll event. Despite trying numerous variations to capt ...

The print screen button in Internet Explorer is not functioning the same way as in other browsers when using JavaScript

Recently, I implemented a JavaScript code that restricts Normal users (non-professionals) from using print screen, Ctrl+A, and Ctrl+C functionalities on the browser. While this code works seamlessly on Firefox and Chrome, it seems to have intermittent su ...