Struggling with the camera in three.js?

I'm struggling to understand how to utilize the three.js camera effectively.

https://i.sstatic.net/7sYb8.png

My goal is to have a small map where players can spawn at the corners, depicted as cubes labeled 1, 2, 3, and 4 on the sketch provided.

My aim is for the camera to initially be positioned behind the players, represented by the "eye" icon in my sketch, pointing towards cube 1 with an orange line indicating the line of sight. I've also illustrated where I want the camera to be if I were the fourth player.

However, during testing, I encountered unexpected behavior. Currently, this is what I am attempting:

camera.position.set(player.position.x, player.position.y + 2, player.position.z + 3);
camera.lookAt(player.position);

The player variable refers to a THREE.Mesh object. While the camera positioning works correctly when the player spawns in positions 1 or 3, it behaves incorrectly in position 2. When I try to rotate around the player using the mouse, the camera rotates as if it's spinning on the Y-axis and obscures my view of the cube. Initially, I believed that utilizing the lookAt() method on the player would align the camera properly, but evidently, I was mistaken.

Could someone clarify why this isn't functioning as expected?

Answer №1

It's a bit challenging to provide specific guidance without reviewing your code, but I've created a sample that aligns with your description. This example utilizes the lookAt function on an object containing x, y, and z coordinates...

http://jsfiddle.net/vn4t6o6u/1/

var camera, scene, renderer, geometry, material, mesh;

init();
animate();

function init() {

    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000);

    // Positioning the camera along the x-axis

    scene.add(camera);
    camera.position.set(-6, -6, 30);
    camera.up = new THREE.Vector3(0, 0, 1);
    camera.lookAt({x: 0, y: 0, z: 0});
    
    setTimeout(function(){
        camera.position.set(14, -6, 30);
        camera.lookAt({x: 8, y: 0, z: 0});  
    }, 1000)
    
    setTimeout(function(){
        camera.position.set(-6, 14, 30);
        camera.lookAt({x: 0, y: 8, z: 0});  
    }, 2000)
    
    setTimeout(function(){
        camera.position.set(14, 14, 30);
        camera.lookAt({x: 8, y: 8, z: 0});  
    }, 3000)

    geometry1 = new THREE.CubeGeometry(2, 2, 2);
    geometry2 = new THREE.CubeGeometry(2, 2, 2);
    geometry3 = new THREE.CubeGeometry(2, 2, 2);
    geometry4 = new THREE.CubeGeometry(2, 2, 2);

    material1 = new THREE.MeshLambertMaterial({color: 0xff0000});
    material2 = new THREE.MeshLambertMaterial({color: 0x00ff00});
    material3 = new THREE.MeshLambertMaterial({color: 0x0000ff});
    material4 = new THREE.MeshLambertMaterial({color: 0x00ffff});

    mesh1 = new THREE.Mesh(geometry1, material1);
    mesh2 = new THREE.Mesh(geometry2, material2);    
    mesh3 = new THREE.Mesh(geometry3, material3);    
    mesh4 = new THREE.Mesh(geometry4, material4);    

    mesh1.position.set(0, 0, 0);
    mesh2.position.set(8, 0, 0);
    mesh3.position.set(0, 8, 0);
    mesh4.position.set(8, 8, 0);

    scene.add(mesh1);
    scene.add(mesh2);
    scene.add(mesh3);
    scene.add(mesh4);

    renderer = new THREE.CanvasRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);

    document.body.appendChild(renderer.domElement);

}

function animate() {
    requestAnimationFrame(animate);
    render();
}

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

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

What is the best way to call a JavaScript function with multiple arguments from a Silverlight project?

I encountered an issue when trying to invoke a JavaScript function with multiple arguments from an HTML page. Here is what I am attempting to do: wbNavigator.Navigate(new Uri("http://localhost:56433/route.html", UriKind.Absolute)); object results = wbNavi ...

Transmit information via AJAX using the React Flux design pattern

Here is my React code snippet: var AddRecord = React.createClass({ getInitialState: function() { return { Data: [] } }, sendData : ...

Convert data in JavaScript and send it as a string in PHP

I'm currently facing a small issue with my JavaScript code. Specifically, I am using AJAX and attempting to retrieve a variable in PHP. Everything seems to be working fine except for the "param" data. Below is the snippet of my code: $('#sign ...

Manipulating content for insertion using jQuery's .html() method

Need help with accepting user input and displaying it in a textarea for editing. Having trouble with jQuery's html() function interpreting HTML entities as real HTML and injecting user scripts into the page. Original code snippet: <textarea name= ...

Using Array.Map() to retrieve the child array within a React component

Here is the data I have retrieved from an API: [ { "id": 1, "appName": "string", "defaultAction": "string", "defaultMessage": "string", "rules": [ { "id": 1, "version": "string", "brand": "string", ...

What are the best methods for adjusting the size of a game's

I create games using HTML5/CSS/JS, but I am struggling to figure out how to make them scale to different screen resolutions. It seems like a simple task, but I can't seem to grasp it. SOLVED var RATIO = 480 / 800; // Initial ratio. function resize() ...

"Deactivate the escaping feature in PHP when using heredoc syntax

My PHP code generates minified JS output using the heredoc. Take a look at this snippet: function prerefresh(){$("#len").empty();predata.forEach(item)} I've highlighted that the {$ is causing issues with variable escaping in my heredoc. Is there a ...

Webdriverio: exploring the window object

I am experimenting with Webdriverio Testrunner using Selenium Standalone. I have encountered an issue while trying to check a global variable (window.myVar) in one of my tests. When attempting to return the window object, I am getting unexpected results i ...

maintaining a specific variable within React

I am working on integrating pagination into my app. I have written the code below, but unfortunately, I am encountering an issue. Below is the implementation of my useEffect: useEffect(() => { let x = null; const unsubscribe = chatsRef . ...

A React child error has occurred in Next.js due to invalid objects being used

Within my project, I have integrated the latest version of next.js and encountered an issue where objects are not valid as a React.js child. https://i.stack.imgur.com/MCO7z.png The problem arises after importing the Head component from Next.js and implem ...

Generating fresh line with knockout effect

Currently in the process of developing a Single Page Application (SPA). Utilizing knockout and observable array to iterate through a json array. Encountering an issue where there are br tags present within the text, but when using data-bind="text: myVar" ...

Is there a way to completely define CSS animation using only JavaScript?

I am looking to implement CSS animation on HTML elements that are generated entirely through a JavaScript function. The approach I am taking involves customizing settings and functions for each part of the animation, which is why this method is necessary. ...

What is the reason behind taps in TypeScript only registering the first tap event?

One issue I am encountering is that only the first tap works when clicked, and subsequent taps result in an error message: Uncaught TypeError: Cannot read properties of undefined (reading 'classList') Here is the code I am using: https://codepen ...

Automatically divide the interface into essential components and additional features

Consider the following interfaces: interface ButtonProps { text: string; } interface DescriptiveButtonProps extends ButtonProps { visible: boolean, description: string; } Now, let's say we want to render a DescriptiveButton that utilize ...

Enhancing the efficiency of a TypeScript-written file content parsing class

Seeking advice on optimizing a typescript module used by a VSCode extension. This module accepts a directory and parses the content within the files, which can be time-consuming for directories with a large number of files. To avoid copying the entire cla ...

The web page's content remains hidden until it is scrolled into view, despite the fact that the page has finished loading

I'm a beginner with Angular and currently working on creating a website. On the following page , when viewed on mobile, I am experiencing an issue where the content doesn't load until it's brought into view by scrolling down the page. I am u ...

js TouchEvent: When performing a pinch gesture with two fingers and lifting one of them up, how can you determine which finger was lifted?

I am currently working on a challenging touching gesture and have encountered the following issue: let cachedStartTouches: TouchList; let cachedMoveTouches: TouchList; function onStart(ev: TouchEvent) { // length equals 2 when two fingers pinch start ...

Is it possible to use async/await with the React setState method?

Seeking clarification on the use of async/await in React setState method. I previously believed it only functioned with Promises, but I have not found any definitive documentation supporting this. Any assistance would be greatly appreciated! In my applica ...

Navigating using Backbone Marionette URL to Server Endpoint

I need to implement client-side validation to check if the user is logged in, and if not, redirect them to the sign-in page. The issue is that the sign-in page exists outside of my Backbone Marionette app. Is there a way in Marionette, Backbone, jQuery, or ...

Tips for maintaining consistency between server-side Java and client-side JS DTO properties

Greetings, I am in search of a solution or plugin within Eclipse that can ensure synchronization between server-side Java DTO properties and their corresponding client-side JSON elements as the codebase evolves. For instance, in a web application with a Ja ...