The camera steadily advances in WebVR Cardboard using three.js technology, never stopping its forward movement

I've been experimenting with trying to create a smooth, continuous forward movement for the camera in a three.js/WebVR project, specifically with only a cardboard viewer needed.

After much trial and error, I've discovered that the usual camera movement methods don't seem to work in WebVR, possibly due to the way the perspective camera is handled in this environment.

For example, this code snippet didn't produce the desired effect:

function render() {
    camera.translateZ(-0.02);
    renderer.render( scene, camera );
}

Instead of moving the camera itself, I tried attaching it to another object and moving that object:

var cube = new THREE.Mesh( geometry, material );
scene.add( cube );
cube.add(camera);
...
function render() {
    cube.translateZ(-0.02);
    cube.rotation.copy(camera.rotation);
    renderer.render( scene, camera );
}

While this method partially worked by moving the camera with the cube, the rotation was off. It felt like in order to move eastward while facing north, I had to rotate 180 degrees to face south.

I suspect there might be some confusion between quaternion and euler rotation, or perhaps I'm missing something with vector3 positioning?

Any suggestions or tips would be greatly appreciated!

Answer №1

To begin, create an empty GameObject and set it as the parent of the MainCamera. Then, add this script to the empty GameObject.

GameObject cameraMain;
float speed = 2f;

void Start () {
    cameraMain = GameObject.FindGameObjectWithTag("MainCamera");
}

void Update () {
    transform.localPosition += transform.forward * speed * Time.deltaTime;
    transform.localRotation = Quaternion.Euler(cameraMain.transform.localEulerAngles.x, cameraMain.transform.localEulerAngles.y, cameraMain.transform.localEulerAngles.z);
}

Answer №2

If you're looking to enhance your video recording skills, creating a dolly is essential. Check out this informative video that demonstrates why and how: https://www.youtube.com/watch?v=mpVG2Iitkqg

Alternatively, here's a simpler approach. Imagine you have a camera and a scene:

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 1000 );

Next, construct a dolly for the camera:

const train = new THREE.Object3D();
scene.add( train );
train.add( camera );

During the animation loop, start by resetting the camera's position to match the train's position, ensuring alignment. Then proceed to move the camera in the direction it is facing, while simultaneously allowing the train to catch up.

renderer.setAnimationLoop( function () {
    if (renderer.xr.isPresenting) {
        camera.position.copy(train.position);
        camera.translateZ( - 0.005 ); // Used to advance the camera forward along its local negative-z axis. Note: This does not function in xr mode.
        train.position.copy(camera.position);
    }
} 

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

Extracting address from a string containing HTML line breaks and apostrophes using JavaScript

I need help with parsing an address that is in a string format like the following: "1234 Something Street<br>Chicago, IL 34571<br>" I am struggling to extract and assign it to separate variables: var street = ...; var city = ...; var state = ...

Having difficulty sending string values with Axios and FormData in Vue.js

Is there a way to send both a file input and text input in a single request using Axios and FormData in Vue.js? I've come across a solution that seems straightforward: const formData = new FormData(); formData.append('file', file); formData. ...

recording the results of a Node.js program in PHP using exec

I'm attempting to retrieve the output from my node.js script using PHP exec wrapped within an ajax call. I am able to make the call and receive some feedback, but I can't seem to capture the console.log output in the variable. This is how I exec ...

Using mousedown, mousemove, and mouseup to handle touch events in vanilla JavaScript instead of jQuery

Can someone guide me on how to set up a touch event handler in JavaScript using the mousedown, mousemove, and mouseup events? I would really appreciate any suggestions or tips! ...

Getting an Object in PostgreSQL without the need for square brackets wrapping when using Node.js and Express

I'm currently utilizing PostgreSQL alongside node-postgres: pool, Node.js, and express to execute some basic queries. The issue I encounter is that the returned object is wrapped within square brackets, but my preference is to receive it without them. ...

Node.js is known for its ability to export both reference and pointer values

Having an issue with exporting my routing table from my express application. In the /bin/www.js file, there is a global variable representing the routing table: var routingTable = []; To create a simple route, new routing objects are pushed using the se ...

Troubleshooting Issue 415: Adding and modifying database records through jQuery AJAX in ASP.NET 6.0 MVC Application

Implementing the Add/Edit functionality for categories in my project led me to utilize a modal (pop-up) to transfer data to the backend without refreshing the page. To achieve this seamless interaction, I opted for ajax integration. However, encountering a ...

Expanding the capabilities of search and replace in Javascript is imperative for enhancing its

I have developed a search and replace function. How can I enhance it by adding a comment or alert to describe the pattern and incorporating a functional input box? Any suggestions are welcome! <html> <head> <title> Search & Replace ...

Establishing Accessor and Mutator Methods

The variables startStopA... and InitialValueA... that were originally in the component TableFields.vue need to be relocated to the store file index.js. However, upon moving them to the store, an error appears stating that setters are not set. I have extens ...

Animating Divs with jQuery to Expand their Size

I am currently designing a services page for my portfolio website. The layout consists of three columns, with the central column containing a large box and the left and right columns each containing three smaller boxes. These smaller boxes function as clic ...

Remove data from Firebase that is older than two hours

I need to implement a solution to automatically delete data that is older than two hours. Currently, I am iterating through all the data on the client-side and deleting outdated entries. However, this approach triggers the db.on('value') function ...

React to the animated scaling

I'm attempting to animate the scale of my react component. Although it seems straightforward, I've run into some issues while following a similar example from the React-Motion demos: var customComponent = () => { let newStyle = { scale: sprin ...

I can't seem to understand why the error "bash: ng: command not found" keeps popping up even though I

Ever since I installed Angular CLI and started working with Angular, something strange happened - the ng command suddenly became not found: ng serve -o Here's a screenshot for reference: bash: ng: command not found Oddly enough, when I use the npx c ...

Is there a way to identify whether the image file is present in my specific situation?

I have a collection of images laid out as shown below image1.png image2.png image3.png image4.png … … image20.png secondImg1.png secondImg2.png secondImg3.png secondImg4.png secondImg5.png ……. …….. secondImg18.png My goal is to dynamically ...

Access data from previous request and transmit it to another request in a Node.js environment

I am facing a situation where I need to extract the parsed json response from a variable in a POST request, store it in a new variable, and then pass that variable in the headers for a subsequent GET request. However, my current approach is not yielding th ...

javascript context scope

As I delve into the world of JavaScript, please bear with me as I navigate through defining multiple namespaces. Here's an example of how I'm doing it: var name_Class = function(){ this.variable_name_1 = {} this.method_name_1 = function() { ...

Verification is required for additional elements within the div block once a single checkbox has been selected

Currently, I am working in PHP using the CodeIgniter framework. I have a question regarding implementing a functionality with checkboxes and validation using jQuery. Here is the scenario I want to achieve: There are four checkboxes, and when one checkbox ...

If the currency is not in USD, please refrain from using the $ symbol before the amount

Is it possible to modify this function so that when the currency is not USD, the $ sign is not added in front of the amount? var convertToCurrency = number => { if (!number) return ''; return new Intl.NumberFormat('en', { ...

What steps can I take to reset my JavaScript code once its original purpose has been fulfilled?

I created this code, learning as I went along. It measures Beats Per Minute as one clicks the left-mouse-button each time they feel a pulse. After 10 clicks, the JavaScript code takes all the values in the array and calculates an average BPM. The issue ar ...

What could be causing the issue of req.body being undefined within the destination function of Multer's diskStorage?

I'm currently utilizing Multer for managing file uploads within my Express.js application. However, I've encountered an issue when attempting to access the req.body values in the destination function of Multer's diskStorage option – it con ...