Track the movement of the mouse to illuminate objects in a three.js environment

Recently delving into the realm of three.js, I am seeking to achieve a solution reminiscent of this older thread with a slight tweak.

The objective is to have a stationary sphere at the center of the scene while having the point light in the scene track the mouse movement. The example referenced prior demonstrates the opposite behavior.

In the process of learning JavaScript and jQuery, grasping the intricacies of three.js has proven challenging. Below is the code I've put together so far, albeit without success:

// Global variables
var container,
scene, 
camera,
renderer,
plane,
mouseMesh;

// Custom global variables
var mouse = {x: 0, y: 0};

init();
animate();

function init() {

// Setting up the scene
scene = new THREE.Scene();

window.addEventListener('resize', function() {
  var WIDTH = window.innerWidth,
      HEIGHT = window.innerHeight;
  renderer.setSize(WIDTH, HEIGHT);
  camera.aspect = WIDTH / HEIGHT;
  camera.updateProjectionMatrix();
});

// Initializing Camera
var screenWidth = window.innerWidth,
        screenHeight = window.innerHeight,
        viewAngle = 75,
        nearDistance = 0.1,
        farDistance = 1000;
camera = new THREE.PerspectiveCamera(viewAngle, screenWidth /   screenHeight, nearDistance, farDistance);
scene.add(camera);
camera.position.set(0, 0, 5);
camera.lookAt(scene.position);

// Setting up Renderer engine with background
renderer = new THREE.WebGLRenderer({
        antialias: true,
    alpha: true
});
renderer.setSize(screenWidth, screenHeight);
container = document.getElementById('container');
container.appendChild(renderer.domElement); 

// Defining lights for the scene
var light = new THREE.PointLight(0xff00ff);
light.position.set(0, 0, 5);
scene.add(light);
var lightAmb = new THREE.AmbientLight(0x000000);
scene.add(lightAmb);

// Creating and moving a circle around the mouse
// The sphere remains transparent
var mouseGeometry = new THREE.SphereGeometry(1, 0, 1);
var mouseMaterial = new THREE.MeshLambertMaterial({  });
mouseMesh = new THREE.Mesh(mouseGeometry, mouseMaterial);

mouseMesh.position.set(0, 0, 5);
scene.add(mouseMesh);

// Trigger given function when mouse moves
document.addEventListener('mousemove', onMouseMove, false);
}

// Tracking mouse movements
function onMouseMove(event) {

// Updating mouse position
event.preventDefault();
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;

// Making the sphere follow the mouse
var vector = new THREE.Vector3(mouse.x, mouse.y, 0.5);
vector.unproject( camera );
var dir = vector.sub( camera.position ).normalize();
var distance = - camera.position.z / dir.z;
var pos = camera.position.clone().add( dir.multiplyScalar( distance )     );
mouseMesh.position.copy(pos);
};

// Animating elements
function animate() {
requestAnimationFrame(animate);
    render();   
}

// Rendering elements
function render() {
renderer.autoClear = false;
renderer.clear();
renderer.render(scene, camera);
};

An attempt was made to replace mouseMesh.position.copy(pos); with light.position.copy(pos);, which unfortunately resulted in the disappearance of mouseMesh.

Answer №1

The mouseMesh disappeared because it moved outside the camera's field of view. Additionally, there was an issue with accessing the light variable within the onMouseMove function.

I have created a codepen example where you can see the point light now following the mouse cursor while the mouseMesh remains static:

http://codepen.io/paulmg/pen/yJAwgx?editors=0010

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

IE11 Error: Script1003 expected but not found

I'm in the process of adding IE11 support, but encountering the following errors: SCRIPT1003: Expected ':' File: vendor.bundle.js, Line: 8699, Column: 8 SCRIPT5009: 'webpackJsonp' is undefined File: app.bundle.js, Line: 1, Colum ...

Obtain information using AJAX calls with jQuery Flot

Having an issue with jQuery Flot that I need help resolving. PHP output (not in JSON format): [[1, 153], [2, 513], [3, 644]] ~~ [[1, 1553], [2, 1903], [3, 2680]] Here is the jQuery call: $.ajax({ url: 'xxx.php', success: function (dat ...

Disabling a chosen option within a dropdown menu

`Hello there, I am just starting out with JavaScript and jQuery. Currently, I am developing a web application for ordering food and drinks. I have a dropdown menu for selecting breakfast items and the quantity. When the "add" button is clicked, a dynamic ...

What is the best way to structure a data object in Javascript or VueJs?

As I work on developing a small application using VueJs, the data I receive is structured in a particular format: { "interactions":[ { "id":14, "user_id":1, "schedule":"2017-06-04 05:02:12", "typ ...

Using the npm package in JavaScript results in a return value of 1

Recently, I have been working on turning this into an npm package: Test.tsx: import React from "react"; export default class Test extends React.Component { public render() { return ( <h1> Hallo & ...

Integrating new components into JSON data

I started by creating a JSON document in my code using the following syntax: let jsonData = []; To populate this document, I utilized the '.push()' method to add elements in this manner: jsonData.push({type: "example", value: "123"}); Eventua ...

Reveal the MongoDB database connection to different sections within a Next.js 6 application

Currently developing an application using Next.js v6, and aiming to populate pages with information from a local mongodb database. My goal is to achieve something similar to the example provided in the tutorial, but with a twist - instead of utilizing an ...

Designing a personalized look for a property with Styled-System

Styled-System offers various props related to css grid: I have a suggestion for a new prop, gridWrap. My idea is to allow users to adjust the auto-fit value using the gridWrap prop. Here's the base CSS code: grid-template-columns: repeat(auto-fit, mi ...

What is the most efficient way to loop through an array and send each item to a method, ensuring that all methods are executed synchronously?

I need to make a request method call that retrieves its own body as an array, which is one item within another array. To achieve this, I have to iterate over the parent array and pass each of its items to the request method for a new server request. I tr ...

Executing a JavaScript function across multiple elements: A step-by-step guide

I recently came across this code snippet on w3schools.com: <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> * {box-sizing: border-box} body {font-family: Verdana, ...

What is the best way to divide the Jquery.js file into smaller, separate files?

My web server has a strict file size limit of 64KB and I heavily rely on jQuery for my project. Unfortunately, using any other library like zepto is not an option. The minified size of jQuery alone is 95KB, so I need to split it into two smaller files. C ...

What's the deal with the max element indices/vertices in WebGL2?

In the process of developing a web component using WebGL2 (and three.js) with OES_element_index_uint enabled, I encountered an unexpected anomaly. When drawing a geometry using indexed vertices, strange lines appeared across the middle of the figure: http ...

Setting up Webpack for my typescript React project using Webpack Version 4.39.2

I have been given the task of fixing the Webpack build in a project that I am currently working on. Despite not being an expert in Webpack, I am facing difficulties trying to make it work. The project has an unconventional react frontend with typescript. I ...

Reaching out to the Edge: Enhancing the jQuery Slider Experience

Alright, I'm really excited about using this amazing slider. What I love most is the "free mode" feature that creates this stunning sliding effect. The size and number of slides are absolutely perfect for me. But there's just one small adjustment ...

Using the toggle method or IF statements in JavaScript to implement show and hide functionality upon clicking

I’ve been struggling with this issue for days now. It seems like I may have overcomplicated a simple piece of code. I'm trying to show some divs when a button is clicked, but I’m having trouble getting it to work properly. Initially, I used VAR.st ...

Converting JavaScript code to React requires excluding jQuery

I have been working on updating my old JavaScript code to make it compatible with React. The main goal is to integrate external data into a 3rd party form. Here is the original JS code: <script charset="utf-8" type="text/javascript" ...

Next.js struggled to load an external image containing an extension within the URL

I am currently dealing with products that have images sourced from various remote servers. I am now looking to incorporate next.js images into the mix. However, after making some updates to the code, images from one server are no longer displaying properly ...

Material-Table does not allow resizing of columns if there are more than 5 columns present

I'm currently using the material-table library to present my data. Despite my attempts, setting a fixed size for each of my 19 columns isn't working as intended. Using width: 45% doesn't produce the expected visual result. Also, implementing ...

How to handle the discrepancy between NextJS exporting files with a .html extension, yet in the <Link> component there is no .html specified

I have been working on my NextJS application and I've realized that all the links within it are built using the <Link href="/my-page"><a>My page</a></Link> component. After exporting the app to generate a static site, ...

Make window.print() trigger the download of a PDF file

Recently, I added a new feature to my website allowing users to download the site's content by following these instructions: Printing with Javascript || Mozilla Dev. Essentially, the user can print a newly formatted site stored in a hidden iframe. Now ...