Attempting to program a bot to navigate in a random pattern across a two-dimensional xz plane using Threejs

My journey began with the code below, which initiates a block moving in a straight line:

const bot_geometry = new THREE.BoxGeometry(1,1,1);
const bot_material = new THREE.MeshBasicMaterial( {color: 0x7777ff, wireframe:   false} );
const bot = new THREE.Mesh( bot_geometry, bot_material );

bot.position.x = 1;
bot.position.y = 0;
bot.position.z = 1;
scene.add(bot);

//create random directions for bot
let direction = new THREE.Vector3(0.001, 0, 0.002); // amount to move per frame

    function animate() {
              bot.position.add(direction); // add to position
              requestAnimationFrame(animate); // keep looping
            }
requestAnimationFrame(animate);

I attempted to make it move randomly on the plane by using the two following lines of code, but now I am faced with two blocks moving in opposite directions along a straight line. Is there a straightforward method to have just one block move randomly on the plane?:

let reverseDirection = Math.floor(Math.random()*2) == 1 ? 1 : -1; 
let direction = new THREE.Vector3(0.001*reverseDirection, 0, 0.002*reverseDirection);

Answer №1

To introduce random direction, use the following formula:

direction = new THREE.Vector3(Math.random() * 2 - 1, 0, Math.random() * 2 - 1).normalize();

You can also define global variables like so:

var direction;
var speed = 5; // moving at 5 units per second
var clock = new THREE.Clock();
var delta;
var shift = new THREE.Vector3();

In your animation loop, include this code snippet:

delta = clock.getDelta();

shift.copy(direction).multiplyScalar(delta * speed);
bot.position.add(shift);

View a working example on JSFiddle.

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

Unit testing in JavaScript has its limitations, one of which is the inability to verify if a

Currently, I am working with an Angular application that includes a simple directive called animate. My goal is to use Jasmine to verify if the slideDown method is being called. Below is the current setup of my directive: animateDirective var animate = f ...

Is there a version of globe (the Chrome experiment) that has been converted to the newest iteration of three.js?

Abridged tale: The code for the globe is currently based on threejs v40, while the latest version on Github is threejs r55. I'm curious if anyone with more expertise in this area has updated the globe to a newer version of three.js? Extended saga: ...

JQuery is failing to properly return the string containing special characters like apostrophes

Storing the name "Uncle Bob's Organic" in the data-Iname attribute caused a retrieval issue, as it only retrieved up to "Uncle Bob". Here is the process used for retrieving the value from the data-Iname: var itemName = $(this).attr("data-Iname"); T ...

Inquiries regarding node.js

While delving into research on node.js and Mongodb, I encountered a few areas that require clarification. My aim is to query Mongodb from the web using JavaScript because of my familiarity with the language. Additionally, it aligns well with Mongodb' ...

Sending an AJAX request to a REST service in order to submit the information captured in an HTML form

<html> <body> <form method="POST"> <label>username</lable> <input id="username" name="username" type="text"> <label>emailid</lable> <input id="emailid" ...

.parseXML yields no results

I am struggling to interpret a response from a server that should be in XML format. While I am new to web development, I am trying to quickly grasp JavaScript for an assignment. Unfortunately, I cannot control the server. My code snippet is as follows: . ...

In Javascript, merge two arrays together in a specific format

Can we transform two arrays into a specific format so I can create my D3 graph? Here are the two arrays I have: date = ["sept,09 2015","sept, 10 2015","sept, 11 2015"] likes = [2,4,5] I need to convert them to this format: [{ date: '...', lik ...

Issue with React Native TextInput failing to update state within a functional component when onChange event is triggered

When using a TextInput in a React Native functional component, I am facing an issue where the state for "name" is not updating properly when onChange occurs. To debug this issue, I have added a console log in useEffect to monitor the new state value. Howe ...

declaration of function interface and property that cannot be modified

After reviewing some new TypeScript code, I encountered a part that left me puzzled. interface test { (a: number): number; readonly b: number; } While I understand that (a:number): number signifies a function where the argument is a:number and the ret ...

Error injecting angular.bootstrap in Angular 1.6.5 version

I have a MeanJS.org skeleton app that I've transformed into hapi-js from express, switched to postgres from mongo, and incorporated OAUTH for authentication (mainly because I liked the server/client module folder structure - haha). Everything seems t ...

Struggling with setting up a PHP and Ajax registration and login system

Struggling with my code and in need of assistance. Desperately trying to set up a register form where users can input their username and password to sign up. Planning to utilize ajax, however, the integration seems faulty. For testing purposes, I tried ech ...

Obtain SVG icons seamlessly in Next.js

My goal was to dynamically retrieve SVG icons, and I discovered a method to achieve this. However, it seems like I have made some errors along the way. Can you point out where I am going wrong? Icon.js import React from "react"; import { ReactCo ...

Using AngularJs to implement a $watch feature that enables two-way binding

I am in the process of designing a webpage that includes multiple range sliders that interact with each other based on their settings. Currently, I have a watch function set up that allows this interaction to occur one way. However, I am interested in havi ...

Interactive image map with hover effects and external image swapping placed beyond the container

I've encountered a problem with a responsive image map and rollovers. Using Matt Stow's responsive image jQuery plugin ensures that coordinates are responsive, and clicking on an area brings up Lightview as expected. However, the issue arises whe ...

Effortless Inertia Scrolling Implemented in Next.js

My search for achieving smooth inertia scrolling in next.js has left me unimpressed with the available solutions, as they either lack performance or come with some drawback. This medium article and sandbox demo provided a choppy experience, While this jav ...

Conceal div elements containing identical information by utilizing jQuery

I'm dealing with a webpage that pulls in a long section of divs from another application. Unfortunately, I can't filter the divs before they appear, but I urgently need to hide any duplicate data within certain values using jQuery. The duplicate ...

Unable to subscribe due to the return value being an AnonymousSubject rather than an Observable

I am facing an issue in Angular 4 where I am attempting to retrieve details from a specific user when clicking on the 'user link profile'. However, I am unable to subscribe to my function because the return value of switchMap is AnonymousSubject ...

How can I apply various textures in three.js?

Hello there! I'm diving into the world of threejs and currently working on a block game similar to Minecraft. Instead of relying solely on objects, I've decided to build my program using planes (specifically the PlaneGeometry class). As I wrap ...

What is the best way to create a reusable component for a dialog box or modal window?

I have been working on developing a reusable dialog component with a yes or no button at the bottom. The main idea behind this is to create a user confirmation dialog that prompts the user to confirm their entered information before proceeding. import Re ...