Positioning the camera directly behind the mesh for optimal framing

I designed a city and a character using Blender, then imported both as JSON objects into my script. My objective is to navigate my character through the city with the character always centered on the screen. However, I'm facing an issue where my character appears on the right side of the screen instead of the center. Can anyone provide guidance on how to position my character at the center of the screen with the camera?

Below is an image of my current screen layout.

    var scene, renderer, camera, lua;
    var keyboard = new THREEx.KeyboardState();
    var clock = new THREE.Clock();
    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(90,window.innerWidth/window.innerHeight,0.1,50000);
    renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setClearColor (0xffffff, 1);
    document.body.appendChild(renderer.domElement);
    var loader = new THREE.JSONLoader();
    loader.load("city.json", function(geomtry , materials){
        var material = new THREE.MeshFaceMaterial(materials);
        var city = new THREE.Mesh(geomtry,material);
        scene.add(city);
    })
    //my character
    loader.load("lua2.json", function (geometry, materials){
        var m = THREE.MeshFaceMaterial(materials);
        lua = new THREE.Mesh(geometry,m);
        //lua.position.set(0,3,0);
        lua.position.set(0,2,0);
        scene.add(lua);
    })
    camera.lookAt(scene);
        var light = new THREE.PointLight();
        //light.position.set(-100,200,100);
        light.position.set(0,500,0);
        scene.add(light);

        var render = function () {
            requestAnimationFrame( render );
            renderer.render(scene, camera);
            update(); 
        };

        function update()
        {
            var delta = clock.getDelta();
            var moveDistance = 5 * delta; 
            var rotateAngle = Math.PI / 2 * delta;     
            // local transformations
            // move forwards/backwards/left/right
            if ( keyboard.pressed("S") )
                lua.translateZ( -moveDistance );
            if ( keyboard.pressed("Z") )
                lua.translateZ(  moveDistance );
            if ( keyboard.pressed("D") )
                lua.translateX( -moveDistance );
            if ( keyboard.pressed("Q") )
                lua.translateX(  moveDistance );
            // rotate left/right/up/down
            var rotation_matrix = new THREE.Matrix4().identity();
            if ( keyboard.pressed("Y") )
                lua.rotateOnAxis( new THREE.Vector3(0,1,0), rotateAngle);
            if ( keyboard.pressed("B") )
                lua.rotateOnAxis( new THREE.Vector3(0,1,0), -rotateAngle);
            if ( keyboard.pressed("G") )
                lua.rotateOnAxis( new THREE.Vector3(1,0,0), rotateAngle);
            if ( keyboard.pressed("H") )
                lua.rotateOnAxis( new THREE.Vector3(1,0,0), -rotateAngle);    

            var relativeCameraOffset = new THREE.Vector3(0,0,0);
            var cameraOffset = relativeCameraOffset.applyMatrix4( lua.matrixWorld );
            camera = new THREE.PerspectiveCamera(45,window.innerWidth/window.innerHeight,0.5,50000);
            camera.position.x = lua.position.x;
            camera.position.y = lua.position.y+1;
            camera.position.z = lua.position.z-2;
            //camera.position.x = cameraOffset.x;
            //camera.position.y = cameraOffset.y;
            //camera.position.z = cameraOffset.z;
            camera.lookAt( lua.position );
        }
        render();

Answer №1

Adjusting the location and angle of your camera is possible with the following code:

camera.position.x = 100;
camera.rotation.x = Math.PI;

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

Is it possible to conceal or disregard text elements from the web browser search function by using CTRL+F?

I have a complex web application interface with a dedicated area for content display. Is there a way to ensure that when users utilize the browser's text search function (CTRL+F), the UI elements are ignored and only the actual content is searched? ...

What are some ways to prevent "window.onbeforeunload" from appearing when a form is submitted?

Is there a way to prevent the alert box from appearing when submitting a form using the Submit button below? I want to avoid being prompted to "Leave this page" or "stay on this" after submitting the form. <script> window.onbeforeunload = ...

Implement the AngularJS orderby filter based on a checkbox selection

Is it possible to use the angularJS orderby filter with a checkbox for ordering columns? I currently have this working as expected: <tr ng-repeat="player in players | orderBy:'id':true | rangeFilter:min:max"> <td>{{player.id}}</ ...

The issue I am encountering is that the keyboard controls in JavaScript are not causing the

One of the key elements in my code revolves around JavaScript functionality. I have implemented a feature where objects can be moved by pressing keys such as "down" or "right". However, there seems to be an issue where an object loaded from a .json file is ...

Positioning JQuery sliders

I've been working on a jQuery slider for my header, but I'm encountering an issue where the previous image drops down to the next container instead of staying in place and transitioning smoothly. It seems like there might be an error in my HTML/C ...

What is the functionality behind object inheritance using the clone() method in this implementation?

I am currently exploring kangax's blog post titled Why ECMAScript 5 still does not allow subclassing an array. In this article, he introduces a unique approach to subclassing that deviates from the traditional prototypal method. BaseClass.prototype = ...

What is the best way to display a particular JavaScript variable in an HTML document?

Is there a way to display the value of a Javascript variable in an HTML form, such as showing it on the screen? Below is my JavaScript code: <script type="text/javascript"> var howLongIsThis = myPlayer.duration(); </script> The variable howL ...

Typescript enhances React Native's Pressable component with a pressed property

I'm currently diving into the world of typescript with React, and I've encountered an issue where I can't utilize the pressed prop from Pressable in a React Native app while using typescript. To work around this, I am leveraging styled comp ...

Struggling with adding headers in React application

When I try to include an h1 heading, either the heading doesn't show up if I comment out the buttons, or if I comment out the heading, then the buttons don't display. But when both are included, nothing is displayed. Any suggestions on how to fix ...

The React engine is triggering an error stating "Module not found."

Utilizing react-engine to enable the server with react component access. Through react-engine, you can provide an express react by directing a URL and utilizing res.render. The documentation specifies that you need to supply a path through req.url. app.use ...

Unraveling unicode escape sequences in JavaScript strings

My code includes a string like \uC88B\uC544\uC694. When I use this string in a node repl (v7.4.0), it displays '좋아요' correctly. However, when I try to use the same string in the following code snippet, it does not work as ex ...

how to sort arrays in javascript

When it comes to filtering items based on specific criteria like fruit and vegetable filters, what is the most effective method to retrieve items that meet both filter requirements? fruitfilter: [] = [{fruitname: "apple"} , {fruitname: "orange"}] vegeta ...

Steps to retrieve data (token) from developer tools and incorporate it into a fetch Post request

Is there a simple way to extract data using dev tools and insert it into a fetch request? I am trying to make a POST request through the console, but I am struggling to correctly copy a token. I attempted to use querySelector but instead of finding the t ...

There is a SyntaxError due to an unexpected token "o" in the JSON data. It is not a valid JSON format

This code is designed to check an XML file to see if the email or login inputted by a user is already in use, and then provide a JSON response. The AJAX code for this functionality is as follows: $.ajax({ type: 'post', dat ...

Iterating through an array and setting variables according to asynchronous code

I have created a function to loop through an array, call a promise, and update a variable based on the result. The code seems to be functioning correctly, but I am wondering if there is a more optimal way to write it. Any suggestions are appreciated. Tha ...

Increase the bottom padding or add some extra space to the Bootstrap form or page

I am currently working on enhancing a Bootstrap Form that includes reset/submit buttons positioned at the bottom. A common issue is when iPhone users attempt to click the Submit button, which initially displays Safari icons before requiring an extra tap to ...

How can you effectively manage Click events within a three.js environment?

I'm working with a world map layer as a plane geometry and I need to handle click events on different parts, such as continents or countries. I want to show popup events on specific parts like information, videos, or image data with links. How can I a ...

The dynamic ui-sref attribute in HTML fails to execute, while the href tag functions properly

Before moving to a controller, I make a web service call to GET a request. The response from this request is stored in the variable $rootScope.userSesion. I want this web service to run every time I switch to a different view without having to duplicate th ...

incorporating theme.spacing in the declaration of the theme

The theme setup that I am working with is as follows: export const themeDefault = createTheme({ themeName: 'Default (Mortgage Hub)', spacing: 4, ...typography, palette, components: { MuiButton: { styleOverrides: { root ...

After removing the timezone from the timestamp log, why is it now showing as one day behind?

Within my programming, I store a timestamp in the variable 'var timeStamp = finalData.obj.followers[0].timestp;', which currently outputs '2020-04-15T00:00:00.000Z.' To extract only the date and remove the time zone information, I util ...