The spotlight seems to be detached from the camera incorrectly

I'm having trouble making the spotLight stick to the camera. Even though I can see the light, it seems to be staying in one position. Need help with this issue. Check out the video for a visual reference.

//Camera
camera = new THREE.PerspectiveCamera( 90, window.innerWidth / window.innerHeight, 0.1, 1000 );
camera.position.set( 0, 1, 0 );
//spotLight attached to camera
spotlight = new THREE.SpotLight( 0xffffff, 55 );
spotlight.angle = 0.20*(Math.PI / 3);
spotlight.penumbra = 0.1;
spotlight.decay = 2;
spotlight.distance = 200;
camera.add( spotlight);
camera.add( spotlight.target );
spotlight.target.position.set( 0, 0, 1 );
spotlight.target=camera;
spotlight.position.copy( camera.position );

controls = new PointerLockControls( camera, document.body );
//adding first person camera from PointerLockControls
scene.add( controls.getObject() );

I've also attempted grouping the camera and spotlight together:

const group = new THREE.Group();
group.add(camera);
group.add(spotlight);
spotlight.target=camera;
spotlight.position.copy( camera.position );
controls = new PointerLockControls( group, document.body );

However, this approach didn't work either. Any suggestions on what needs to be changed or added?

//edit this is what my current code looks like

import * as THREE from "../node_modules/three/build/three.module.js";
import { GUI } from './jsm/libs/dat.gui.module.js';

let renderer, scene, camera, gui;
let spotlight, lightHelper;

function init() {
    renderer = new THREE.WebGLRenderer();
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );
    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera( 90, window.innerWidth / window.innerHeight, 0.1, 1000 );
    camera.position.set(0,0,1);
    const boxgeometry = new THREE.BoxGeometry( 25, 25, 25 );
    const boxmaterial = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
    const cube = new THREE.Mesh( boxgeometry, boxmaterial );
    scene.add( cube );
    cube.position.set(-20,0,1);

    const ambient = new THREE.AmbientLight( 0xffffff, 0.2 );
    scene.add(ambient);

    **scene.add(camera);
    spotlight = new THREE.SpotLight(0xffffff, 55, 80, 0.8*Math.PI);
    camera.add(spotlight);
    camera.add(spotlight.target);**

    let material = new THREE.MeshPhongMaterial( { color: 0x808080, dithering: true } );
    let geometry = new THREE.PlaneGeometry( 2000, 2000 );
    let floor= new THREE.Mesh( geometry, material );
    floor.position.set( 0, - 1, 0 );
    floor.rotation.x = - Math.PI * 0.5;
    floor.receiveShadow = true;
    scene.add(floor);
    render();

    window.addEventListener( 'resize', onWindowResize );

}
function animate() 
{
    requestAnimationFrame( animate );
    camera.rotation.y+=0.01;
    renderer.render( scene, camera );
}
animate();

Answer №1

Here is the suggested setup:

let camera, scene, renderer;

initialize();

function initialize() {

  camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10);
  camera.position.z = 1;

  scene = new THREE.Scene();
  scene.add(camera);

  const ambientLight = new THREE.AmbientLight(0xffffff, 0.4);
  scene.add(ambientLight);

  const spotLight = new THREE.SpotLight(0xffffff, 0.6, 0, Math.PI * 0.05);
  camera.add(spotLight);

  const geometry = new THREE.PlaneGeometry();
  const material = new THREE.MeshPhongMaterial();

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

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

}

function animation(time) {

  const t = time * 0.001;

  camera.position.x = Math.sin(t) * 0.25;
  camera.position.y = Math.cos(t) * 0.25;

  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="22564a50474762120c1311160c12">[email protected]</a>/build/three.min.js"></script>

Make sure to attach the spot light as a child of the camera and add the camera itself to the scene.

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

Break down React website into distinct modules and bundle them as npm dependencies within a single package

Currently, I am developing a React website that includes distinct sections such as contact management and message management. Each of these sections is quite extensive. To navigate to these sections, we use a single dashboard for control. Since separate ...

Build a Search Suggestions feature with Node Package Manager (NPM) and Model-View-Controller (M

Stepping into the exciting world of MVC core and harnessing NPM for JavaScript packages has been a learning curve. However, I've encountered an issue that requires some deliberation on the best course of action for resolution. To provide context, I ha ...

How to showcase a list from intricate JSON data using Angular

I recently came across this pre-existing JSON data that I am unable to change: {"tags": [ { "title": "news", "options": [ { "title": "important", }, { "title": "less important", ...

Creating hashbang #! URL patterns for handling REST requests in client-side applications

I'm currently working on a single page application with my own custom router implementation. window.onhashchange = function(event) {... Within the URL structure, I am using hash bangs similar to the following examples: #!/products #!/products/1 #! ...

Having trouble with NPM Moment.js in React: Why is moment__WEBPACK_IMPORTED_MODULE_2__format not functioning properly?

scenario, After resolving my current issue using dateFns (date-fns.org), I am interested in integrating Momentjs into the project as well. The task at hand involves converting data to a string format within an app built with create-react-app. However, wh ...

What is the technique for creating multiple circles using CSS?

Creating multiple circles in CSS and linking them to my HTML file has posed a challenge. The code I have so far is: .circle{ height: 50px; width: 50px; background-color: red; } However, attempting to make another circle using the same 'circle' c ...

Gathering information from a PHP form without redirecting to a new page

Can an array be passed from JavaScript to PHP on the same page before submission? In my index.php, I have a form where changing the value of an input triggers a function to send the input value to PHP. In PHP, this value is used to make an HTTP request to ...

"Unraveling the depths of a multidimensional array in JavaScript: a comprehensive guide

Seeking assistance from this wonderfully helpful community :) It seems like I might be declaring and creating my arrays incorrectly, as I am trying to add content to an array of arrays but unable to retrieve anything from it. Here's the code snippet ...

Guide to implementing a seamless CSS animation on each page change using Next.js

Currently in the process of developing a static website using Next.js. I've successfully implemented a CSS animation that triggers in full screen when a specific div is created. This div has been placed in my _app.tsx file to ensure that the animation ...

Tips for sending an array from a higher-order component to a nested component in React Native using props

I have a scenario where I need to pass an array called "subjects" from the SubjectsScreen component to the MarkAttendanceScreen component and then display that array as a list using FlatList. Parent Component export default class SubjectsScreen extends C ...

Tips for showcasing JavaScript variables on a webpage

I am working with various JavaScript variables that involve displaying values inside div elements. goalDiv = "<div class=goal-parent id=goal-parent"+Id+">"+ "<div class=goal>"+ "<div class=top-layer>"+ "<div class=compone ...

I aim to showcase JSON data within a div element

I'm struggling with retrieving JSON data and displaying it on an HTML element. I've tried multiple methods, but none seem to be working. Here is my code: MYAPP.JS $(document).ready(function() { $(function() { switch (menu) { case &apo ...

Having trouble rendering an object in my ThreeJS project. The error message says: "THREE.OBJLoader: Unexpected line: 'usemap glass'"

I encountered an error while running threejs in an angular 8 application. The objective is to load an object, for which the object and material files were obtained from Kenney assets. Despite referencing examples on the official threejs site and other onli ...

Page reloads are disabled when Chrome devtools debugger is paused in a React app

Currently, I am in the process of troubleshooting a React application that was created using create-react-app. Whenever I attempt to reload the page while paused on a breakpoint, it results in the page stalling. The screen goes blank and is unresponsive t ...

Learn the method of showcasing a JavaScript variable value within an HTML href tag

Currently, I am in the process of rewriting my URL and category name to be passed into the URL. For this purpose, I am creating a URL friendly string using the following JavaScript function: function getUrlFriendlyString(str) { // convert spaces to &ap ...

Display the accurate prompt in the event of 2 `catch` statements

elementX.isPresent() .then(() => { elementX.all(by.cssContainingText('option', text)).click() .catch(error => { throw {message: "Unable to select text in dropdown box"} ...

Highest Positioned jQuery Mobile Section

Requesting something a bit out of the ordinary, I understand. I currently have a jQueryMobile page set up with simplicity: <div data-role="page" class="type-home" id="home"> <div data-role="header" data-theme="b"> <h1>Our To ...

Using Angular JS to apply the ng-class-odd directive within nested ng-repeat loops

I am in the process of creating a flexible table outputter that can handle any number of rows or columns. This is achieved by using nested ng-repeat attributes, as shown below: <table> <tr ng-repeat="row in rowList"> <t ...

Is there a way to modify my function expression without using any state variables?

Currently working on a jQuery game where the player is generated upon clicking a button. Below is the function expression I'm using to store the player's information: var getPlayerData = function() { return { name: $("#name").val(),/ ...

The JQuery get method fails to send a request to the server

When running the following jQuery code to load a partial page onto a hidden div, everything works fine on my local machine. However, once I add the code to the server, the partial page does not load. Any suggestions on why this might be happening? var u ...