I am encountering an issue with manipulating the x, y, and z axes of my three.js sphere

I am encountering an issue while working with Three.js. I followed a tutorial on YouTube (https://www.youtube.com/watch?v=pUgWfqWZWmM) and my problem arises around the 48-minute mark. The mousemove event to move on the x, y, and z axes is not functioning as expected. I discovered this error message here. Apologies for any errors in my English. I hope you all can assist me with this matter.

document.addEventListener('mousmeove', onDocumentMouseMove)

let mouseX = 0;
let mouseY = 0;

let targetX = 0;
let targetY = 0;

const windowX = window.innerWidth / 2;
const windowY = window.innerHeight / 2;

function onDocumentMouseMove(event) {

    mouseX = (event.clientX - windowX)
    mouseY = (event.clientY - windowY)  
}
 
const updateSphere = (event) => {
    sphere.position.y = window.scrollY * .001
}

window.addEventListener('scroll', updateSphere)

const clock = new THREE.Clock()

const tick = () =>
{
    targetX = mouseX * .001
    targetY = mouseY * .001

    const elapsedTime = clock.getElapsedTime()

    // Update objects
    sphere.rotation.y = .5 * elapsedTime

    sphere.rotation.y += .5 * (targetX - sphere.rotation.y)
    sphere.rotation.x += .5 * (targetY - sphere.rotation.x)
    sphere.position.z += .5 * (targetY - sphere.rotation.x)

    // Update Orbital Controls
    // controls.update()

    // Render
    renderer.render(scene, camera)

    // Call tick again on the next frame
    window.requestAnimationFrame(tick)
}

tick()

Answer №1

It appears that the code is functioning as intended. I recommend using the code provided below as a reference. It restructured the application in a slightly different manner compared to your original approach.

const camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10);
let scene = new THREE.Scene();
let renderer;
let sphere;

let mouseX = 0;
let mouseY = 0;

let targetX = 0;
let targetY = 0;

const windowX = window.innerWidth / 2;
const windowY = window.innerHeight / 2;

const clock = new THREE.Clock();

init();
animate();

function init() {
    // Initialize camera position
    camera.position.z = 4;

    const geometry = new THREE.SphereGeometry();
    const material = new THREE.MeshNormalMaterial({
        flatShading: true
    });

    sphere = new THREE.Mesh(geometry, material);
    scene.add(sphere);

    // Create WebGL Renderer
    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    document.addEventListener('mousemove', onDocumentMouseMove);
}

function onDocumentMouseMove(event) {
    mouseX = event.clientX - windowX;
    mouseY = event.clientY - windowY;
}

function animate() {
    requestAnimationFrame(animate);

  targetX = mouseX * 0.001;
  targetY = mouseY * 0.001;

  const elapsedTime = clock.getElapsedTime()

  // Update object rotation
  sphere.rotation.y = 0.5 * elapsedTime;
  sphere.rotation.y += 0.5 * (targetX - sphere.rotation.y)
  sphere.rotation.x += 0.5 * (targetY - sphere.rotation.x)
  sphere.rotation.z += 0.5 * (targetY - sphere.rotation.x)

  renderer.render(scene, camera);
}
body {
      margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="03776b71666643332d3230362d33">[email protected]</a>/build/three.min.js"></script>

Answer №2

Have you visually copied the code snippet from your own project or directly from a tutorial while crafting your question? I'm inquiring because the error message linked here seems to display code that differs from what you've provided. The error note indicates an unfinished line with a multiplication operator at its end.

I suspect the transpiler is interpreting the subsequent line as an extension of the preceding incomplete one:

const elapsedTime = clock.getElapsedTime()

..in simpler terms:

In your query, the structure appears as follows:

targetY = mouseY * 0.001;

const elapsedTime = clock.getElapsedTime()

Whereas, the displayed error script looks like this:

targetY = mouseY *

const elapsedTime = clock.getElapsedTime() 

Kindly double-check if the line before the alleged issue is complete, similar to what's shown in your submission, or partial as seen in the error prompt.

Note: Maintain uniformity in using semicolons to conclude lines of code. Inconsistency may lead to confusion...not desirable!

Additional Note: It's assumed you've resolved the dilemma independently. Nevertheless, informing the community is valuable, even for seemingly trivial errors. It can happen to anyone...the best too!

Embrace your mistakes as they are stepping stones towards becoming a proficient coder...!

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

creating objects dynamically through URL

Attempting to dynamically create a new instance of a mongoose model through a URL request using Express. In the example below, when const kind = 'modelOne' is received via the URL, I encounter an error stating 'Cannot read property 'mo ...

Magento is prompting for admin login in response 302 after executing an AJAX call

I am facing an issue with my AJAX request in Magento block which triggers an action in my module controller. The problem is that the response of this request is a 302 status code, leading to a redirect to the admin sign-in page if I am not logged in. Howev ...

JavaScript Error: String length or allocation size is not valid

My code consists of a series of checkboxes that need to be checked, then if they are checked, a string is added to an array. The goal is to loop through the array and concatenate the strings with commas in between. Unfortunately, every time I run this, err ...

How does the super(props) function impact my React component?

I struggle with using JS and experimenting with React. The React documentation found at this link explains the following: When setting up the constructor for a subclass of React.Component, it is important to call super(props) before any other code. Fa ...

The entity x.x cannot be used as a constructor

I'm having trouble retrieving the model to create a new object of type picture. Here is a snippet of the code I am working with: Endpoint Code: import { picture } from '../models/pictures' //etc.. pics.post('/upload', (req, res) ...

steps to initiate re-render of rating module

My first experience with React has been interesting. I decided to challenge myself by creating a 5-star rating component. All logs are showing up properly, but there seems to be an issue with the component not re-rendering when the state changes. Thank you ...

What is the method for changing the Uint8Array object into a string?

I am encountering a similar issue as the one discussed in this post. I have read the solution provided, but I am having trouble grasping how to implement it. Are there any alternative suggestions? Here is my code snippet: var eccrypto = require("eccrypto ...

Guide on sending formik initialState to a function as an argument

I'm currently working with Formik in my React application and I'm facing some confusion on how to pass a Formik value prop as a parameter into a function. Assume that the Formik values are as follows: "props": { "myJobName&quo ...

What is the best way to detect the presence of the special characters "<" or ">" in a user input using JavaScript?

Looking to identify the presence of < or > in user input using JavaScript. Anyone have a suggestion for the regular expression to use? The current regex is not functioning as expected. var spclChar=/^[<>]$/; if(searchCriteria.firstNa ...

What could be causing my "onChange" function to not work as expected?

export function UpdateData(props){ return( <div> <div className='updateForm'> <form> <div className="form-group"> <label>Your ID:& ...

Why am I seeing a blank page?

I've recently started learning React and I'm facing an issue where the header and paragraph are not showing up on my page. Here's a snippet from my script tag with the type set to text/babel: var myElements = React.createClass({ render: ...

My three.js program isn't displaying anything on the screen, even though I'm confident that my

Currently, I am delving into the world of three.js with the aim of creating a 3D showroom showcasing a few planets. I have managed to create the moon, but alas, all that greets me upon running my code is a dismal black screen. Here's the code I have p ...

The command "actions" in Selenium is not recognized

I am having trouble trying to perform a mouse click based on position. No matter what I try, I keep receiving the same error message. I encountered this issue when attempting a double click on the main search bar of google.com. For assistance, refer to: ...

The console is showing an error message stating that the variable "i" is not

Currently, I am developing the dashboard for my discord.js bot. While working on it, I encountered an issue where a variable I created to select an array from my JSON file is being reported as undefined by the console. $(function() { $.getJSON( "./data/ ...

Adding the Bootstrap script

I am facing an issue with incorporating a Bootstrap navbar into my page using a PHP function. I have already included the Bootstrap CSS file, but now I also need to add the script for a dropdown menu functionality. When I tried placing the script at the en ...

What steps should be taken to ensure that the onmouseover and onmouseout settings function correctly?

The Problem Currently, I have a setup for an online store where the shopping cart can be viewed by hovering over a div in the navigation menu. In my previous prototype, the relationship between the shoppingTab div and the trolley div allowed the shopping ...

What is the most effective way to determine if a statement is either false or undefined?

What is the most effective way to determine if a statement is not true or undefined, sometimes without necessarily being a boolean? I am attempting to improve this code. var result = 'sometimes the result is undefined'; if (result === false || ...

What is the process for retrieving the text element from a React component when using React.cloneElement?

Can I centralize a translation function for all table header elements? const CustomersTable = () => { var headers=<> <th>Name</th> <th>Age</th> <th>Another text</th> </> ...

What is the process for creating an unfold or unwrap animation for a cylinder shape using Three.js?

In an effort to enhance students' understanding of the three surfaces of a cylinder, I am working on creating an unwrap animation for them. My goal is to achieve a similar look to this example on YouTube: By utilizing THREE.CylinderGeometry, I ...

Eliminate server-side functionality from the React project's boilerplate template

After cloning and installing the project from https://github.com/react-boilerplate/react-boilerplate, I realized that I only need the client-side portion as I intend to use a pre-existing server (express) for my application setup. Below is an excerpt f ...