Ineffectiveness of Three.js camera's lookat function

I've been trying to modify the camera's focus point using a Vector3, but for some reason, the camera keeps looking at the scene's origin. I'm a bit perplexed as to why this is happening, especially since all the examples I've come across seemed pretty straightforward. Any thoughts or suggestions?

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="/three.js"></script>
    <script type="text/javascript" src="/MTLLoader.js"></script>
    <script type="text/javascript" src="/OBJLoader.js"></script>

    <script type="text/javascript" src="/stats.js"></script>
    <style>
        body {
            /* set margin to 0 and overflow to hidden, to go fullscreen */
            margin: 0;
            overflow: hidden;
        }
    </style>
</head>
<body>
<script type="text/javascript" src="/World.js"></script>
<script type="text/javascript" src="/Controls.js"></script>
<script type="text/javascript">
    // Initialize our new world object which will 
    //  setup our scene, camera, lights, and renderer.
    var world = new World(true);
    var controls = new Controls();

    // Load the map for this given level. 
    // A reference to every model loaded is saved in world.model[*name_of_file*]
    world.modelLoader('meter_grid');
    world.modelLoader('skybox1');
    world.modelLoader('test_character');

    // Render loop. Important things happens in here.
    (function render() {
        if(world.stats){
            world.stats.update();
        }
        //console.log(JSON.stringify(world.camera.position));
        world.updateRotation(controls.left, controls.right);
        requestAnimationFrame(render);
        world.renderer.render(world.scene, world.camera);
    }());
</script>
<script src="/domevents.js"></script>
</body>
</html>

Check out the "class" below to see how the scene is being constructed

// =======================================================
//  The World.
// =======================================================
var World = function(showStats){

    this.currentTime = (+new Date()) / 1000.0;
    this.stats = showStats ? this.initStats() : false;

    // Create scene object and add fog to scene: Fog( hex, near, far )
    this.scene = new THREE.Scene();

    // Create camera object: PerspectiveCamera( fov, aspect, near, far )
    this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);
    this.camera.position.x = 0;
    this.camera.position.y = 5;
    this.camera.position.z = 5;

    this.look = new THREE.Vector3(5, 0, -5);
    this.camera.lookAt(this.look);

    this.scene.add(this.camera);

    // Create ambient light
    this.light = new THREE.AmbientLight( 0x444444 );
    this.light.intensity = 5;
    this.scene.add( this.light );

    // Create renderer and bind to dom element
    this.renderer = new THREE.WebGLRenderer();
    this.renderer.setClearColor(0xffffff);
    this.renderer.setPixelRatio(window.devicePixelRatio);
    this.renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(this.renderer.domElement);
    this.rotationSpeed = .02;
};

World.prototype.modelLoader = function(filename){
    var scope = this;
    var mtlLoader = new THREE.MTLLoader();
    mtlLoader.setBaseUrl( '/obj_assets/' );
    mtlLoader.setPath( '/obj_assets/' );
    mtlLoader.load( filename + '.mtl', function( materials ) {
        materials.preload();

        var objLoader = new THREE.OBJLoader();
        objLoader.setMaterials( materials );
        objLoader.setPath( '/obj_assets/' );
        objLoader.load( filename + '.obj', function ( object ) {

            object.name = filename;
            scope.scene.add( object );

            if(filename === 'test_character'){
                scope.moveCharacter(filename, 0, 0);
            }
        });
    }); 
};
World.prototype.render = function(){  
    if(this.stats){
        this.stats.update();
    }
    this.controls.update();
    requestAnimationFrame(this.render);
    this.renderer.render(this.scene, this.camera);
};

World.prototype.initStats = function(){
    var stats = new Stats();
    stats.setMode(0); // 0: fps, 1: ms

    // Align top left
    stats.domElement.style.position = 'absolute';
    stats.domElement.style.left = '0px';
    stats.domElement.style.top = '0px';

    document.body.appendChild(stats.domElement);
    return stats;
};

World.prototype.updateRotation = function(key_left, key_right){
    var x = this.camera.position.x,
        y = this.camera.position.y,
        z = this.camera.position.z;
    if (key_right){ 
        this.camera.position.x = x * Math.cos(this.rotationSpeed) + z * Math.sin(this.rotationSpeed);
        this.camera.position.z = z * Math.cos(this.rotationSpeed) - x * Math.sin(this.rotationSpeed);
    } else if (key_left){
        this.camera.position.x = x * Math.cos(this.rotationSpeed) - z * Math.sin(this.rotationSpeed);
        this.camera.position.z = z * Math.cos(this.rotationSpeed) + x * Math.sin(this.rotationSpeed);
    }
    this.camera.lookAt(this.scene.position);
};
// Move the character from a 2D xy grid perspective
World.prototype.moveCharacter = function(name, x, y){

    this.scene.getObjectByName(name).position.x = x;
    this.scene.getObjectByName(name).position.z = -y;    
};

Answer №1

Issue Resolved: After investigating, I discovered that my updateRotation function (as shown in the code snippet) was replacing the original camera.lookAt function with the scene's 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

Incorporating role-specific paths in Vue Router using Pinia

Is it possible to load one of three potential routes based on a user's role in my pinia store? The issue I'm currently facing is that the pinia store doesn't appear to be initialized before the router is set, resulting in the error Uncaught ...

Find keys in an array based on a specified value

I need to retrieve an array of keys from an object that match a specified value ...

Adapting software for use with Panasonic Viera

We are in the process of transferring our current HTML/JavaScript/CSS application to the Panasonic platform. Our current setup involves using JavaScript for generating HTML and CSS for styling the application. The programming language used in the Panasoni ...

What is the best way to turn each function within the module pattern into a promise?

Utilizing Angular 1.5, I have developed a factory function that returns a literal object structured as follows: return { item: null, get: function() { return item; }, create: function() { if (this.get()){ this.remove(); ...

Using assert.rejects() in Mocha and Node: A Complete Guide

Following the instructions in the documentation, I attempted to use assert.rejects to test for an error message (I have Node version above v10). However, no matter what message I specify, the test always passes. What could be causing this issue? it("is f ...

Maintaining the initial value of a textbox in jQuery across various focusin events

Struggling to accurately explain the process, so feel free to check out this helpful fiddle. In my form, there are several text input fields and a single submit button. The submit button becomes enabled once any of the form fields have been altered. If a ...

Shadows on menu buttons transform when clicked using React and CSS

I'm currently working on customizing the styling of a menu using CSS in a project that involves the use of "react-horizontal-scrolling-menu". While I've been successful in styling the menu items with .menu-item:hover & .menu-item:active, I am ...

I must address the drag-and-drop problem in reverse scenarios

I am currently utilizing react-dnd for drag and drop feature in my color-coding system. The implementation works flawlessly when I move a color forward, but encounters an issue when moving backward. Specifically, the problem arises when shifting a color ...

Creating new components within A-frame

I've been attempting to implement the bubble function into my scene to generate a sphere, but unfortunately nothing is showing up. Even when I try creating a sphere without using the bubble function, it still doesn't appear in the scene. func ...

The September/October 2013 release of the Ajax Control Toolkit is causing conflicts with jQuery

After updating our project to utilize the latest October 2013 release of the Ajax Control Toolkit for the HTML editor extender and Ajax file uploader, we encountered unexpected issues. Our ASP.NET 4.0 project, which previously used C#, jQuery 1.9.0, jQuery ...

SignalR enables the display of identical dashboard data pulled from queries on various browsers. By utilizing SignalR/hub, MVC, and C#.NET, the data can

Encountering an issue with my signalr/hub while fetching dashboard data. I'm using 2 browsers to access data based on dates. However, when searching for July on browser 1 and then switching to another month on browser 2, the data in browser 1 gets upd ...

What could be causing the React-Router-Dom Outlet to not show the component?

I am working on a component that houses four different components. const ProtectedRoute = () => { return ( <> <Header /> <div className='flex h-screen overflow-hidden'> <div className="md:block h ...

NodeJS/WebdriverJS: Error - 'Element is not connected to the webpage'

Hello there! I am new to WebDriver (chromedriver) and my knowledge of JavaScript syntax is quite basic, so please excuse me if my code appears messy. Currently, I have a clickAllElements(); function that identifies all elements within a class and performs ...

Is there a way to reverse a string in Javascript without using any built-in functions?

I am looking for a way to reverse a string without using built-in functions like split, reverse, and join. I came across this code snippet on Stack Overflow (), but I'm having trouble understanding what the code does on the fourth line. I need more cl ...

Using React to dynamically assign a backgroundImage based on a JSON response

I am having an issue with retrieving data from my Wordpress API and displaying it in my react app. Specifically, I am struggling to set the post's featured image as a background-image for an element. Here is an example of the JSON response: { "id" ...

Tips on saving every query outcome in a separate array and delivering it back to the controller upon completion

I am currently facing an issue where I receive data in a function from my controller, and inside my model function, I need to retrieve results using a query with a dynamic value of channel. The channel ID will be coming from each checkbox on my HTML view ...

Go to a specific component located in a different module within Angular

I have a default app.component that contains a button. When this button is clicked, I want to navigate to the login.component. Below is a snippet from my app.module.ts file: import { BrowserModule } from '@angular/platform-browser'; ...

Display a thumbnail image using a v-for loop

Looking for help with implementing a photo preview in my code using BootstrapVue. The Vue devtools show that the form-file contains the image, but my 'watch' isn't functioning properly. Any assistance would be greatly appreciated! Here is ...

Displaying 'Undefined' instead of 'Cleared messages count' in the Clear Command

My goal is to display the number of deleted messages on an embed, but when the embed is sent, it shows bot deleted undefined messages. Here's a screenshot: https://i.sstatic.net/2GYxX.png I want it to show bot deleted ex: 15 messages. It works fine ...

Modifying the color of multiple cells simultaneously

I'm currently facing an issue where I need to change the cell color of multiple cells at once, all stored within a specific range. However, I only want certain cells to change based on a particular condition. While I can manually change each cell, it& ...