Positioning the camera for an infinite ThreeJs gaming experience

I am currently learning Three.js and attempting to create my first game: an endless runner.

After reading this article, I aim to create a similar game where the main character, a blue ball, rolls infinitely forward while dodging obstacles that appear in its path. Players can control the ball by moving it left or right and jumping using the keyboard (left/right arrow keys and space bar).

Here is my initial concept: https://i.sstatic.net/RNILd.jpg

While inspired by the article, I intend to understand and not simply copy the code. Here is what I have accomplished so far:

let sceneWidth = window.innerWidth;
let sceneHeight = window.innerHeight;
// Remaining JavaScript code...
<script src="https://threejs.org/build/three.min.js"></script>

(JSFiddle)

However, I am facing several issues, starting with object and camera positioning.

I would like the ground plane's shorter side aligned with the screen edge to ensure full visibility without any parts hidden off-screen. Additionally, I want the ball centered horizontally and positioned near the start of the floor vertically, as shown in the figure, with its shadow cast on the plane. I am using a spotlight and Lambert materials for shadows, but they are not displaying. Why?

I also need help with object placement. While my current code functions, I wonder if there are more efficient ways to handle positioning.

Lastly, I plan to adjust the sphere's radius from 0.03 to 1 and scale down the scene by zooming out the camera. This change will simplify the scene setup.

If anyone has advice or tips, especially regarding setting up the scene correctly, please share!


EDIT 1

I modified

camera.lookAt(new THREE.Vector3(0, 0, 0));
to
camera.lookAt(new THREE.Vector3(0, 0, -5));
and added
spotLight.lookAt(new THREE.Vector3(0, 0, -5));
.

The updated result can be viewed here: https://i.sstatic.net/qF0ns.png

This outcome is not exactly what I had in mind...

Answer №1

Placing your plane and sphere at the origin of the y-axis is correct, but the issue lies in directing the camera straight at (0, 0, 0) using

camera.lookAt(0, 0, 0);

This results in the ball being perfectly centered. To fix this, adjust the camera to look slightly ahead of the sphere. You may need to fine-tune the value, but something like this should work:

camera.lookAt(0, 0, -5);

In addition, your spotlight is currently pointing directly forward. By placing it at (2, 30, 0), its effectiveness diminishes. It's important to direct the spotlight towards your desired area:

spotLight.lookAt(0, 0, -5);

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 reason for the failure of multiple place markers on a planet object3D?

After spending hours trying to debug a piece of code I wrote 3 years ago using Three.js, I still can't figure out why it's not working anymore. I thought updating all the other code to use ES6 for Three.js would solve the issue, but when I try t ...

jQuery allows us to set two separate conditions for two distinct variables

I've written this function: settings_rc_left.on('click', function(){ var settings_list_last_element_id_one = settings_menu_element.attr('id') == 'r_02', settings_list_last_element_id_two = settings_menu_eleme ...

Jesting around with mocking console.error leads to test failures

The Issue: Currently, I am working on testing React components using Jest and Enzyme. In order to check for properties in development, I have incorporated the prop-types module. The prop-types module relies on console.error to alert when mandatory props a ...

Is there a way to have the collapsible content automatically expanded upon loading?

I came across a tutorial on w3school (https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_collapsible_symbol), which demonstrates collapsible content hidden by default. The code snippet from the link is provided below. Can someone assist me in cha ...

Can someone explain the crazy math used in three.js?

I've recently started learning three.js, and I keep encountering these complex mathematical formulas that seem confusing. Take this example for instance: mouse.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeig ...

Implementing bind to invoke a function during an onClick Event

Here is a code snippet I have been working on that demonstrates how to handle click events on hyperlinks. The code features two hyperlinks named A and B. When hyperlink A is clicked, the console will log 'You selected A', and when B is clicked, ...

Show a message on form submission rather than redirecting

I'm working on a simple sign-up form and I want to show a success message directly on the page instead of redirecting to another page after submission. Is it better to display the message as a pop-up, an alert, or just on the page itself? <form a ...

Update the HTML table by changing the first cell in the first row to span multiple

I currently have a table structured like this: <table> <thead> <tr> <th></th> <th>Col1</th> <th>Col2</th> <th>Col3</th> <th>Col4& ...

Zero's JSON Journey

When I make an HTTP request to a JSON server and store the value in a variable, using console.log() displays all the information from the JSON. However, when I try to use interpolation to display this information in the template, it throws the following er ...

Searching with Jquery Ajax

For my search functionality, I am utilizing ajax jquery js. I found this useful code snippet here: However, I am facing some challenges with the following Javascript code: <script language="JavaScript" type="text/javascript"> <!-- function searc ...

Learn the method to conceal rows within a table simply by toggling a button

I need a function that will hide the rows below a row with a header and button, and only reveal them when another row with a header and button is clicked. When one of the +/- buttons is clicked, it should hide or expand all the rows with data content. http ...

Get names with specific characteristics by using a Javascript object that acts as an associative array

Can someone help me with my code? I'm trying to create an input box that, when I type in "A", will display the names of students who have earned "A" grades. I feel like I'm close to getting it right, but there's something missing. Any assist ...

The jQuery file that is included in the main master page is not accessible for the .aspx page that inherits the same master page

In my web development project, I am facing an issue with including the jQuery file in a master page. The structure of my project is as follows: The master page is located in the root directory. The jQuery file is stored in a folder named "script". The sp ...

Is there any method to determine whether a floated element has been pushed down?

Imagine a dynamic menu with floating elements, each set at a width of 150px. As the menu's width decreases, the elements progressively move to the next row. You are contemplating how to detect when an element has been moved down. One approach could b ...

Having trouble with React's useEffect and React-Query's useQuery?

As a React newbie, I'm trying to implement global error handling using a context provider and a custom hook. Main Objective: Implementing a system to handle errors at the global level. The Issue: Errors reappear immediately after being removed. I s ...

Why is it necessary to use quotations and plus symbols when retrieving values of objects from JSON?

Initially, when attempting to call the PunkAPI for the first time, I was trying to include images (urls are an object returned in the JSON) by append("<img src='beer[i].image_url'/>"); Unfortunately, this did not work because (according t ...

Is there a way to deliver information to a specific element on a client's HTML page?

My current project involves using Node.js to serve a webpage that collects user inputs and stores them in a mongodb server. The web page also displays these user inputs. I am trying to determine the best way to pass the user inputs from node.js to the < ...

Javascript Countdown Timer for HTML5 Canvas Animation

I'm currently working on a countdown in javascript using createJS for Flash Canvas HTML5, however, I've encountered the following error: file_Canvas.js:318 Uncaught TypeError: Cannot read property 'dtxt_days' of undefined This error sp ...

Sending property via div

In my ReactJS project, I am working on creating a dynamic div board. To properly position the elements on the board, I need to pass props such as row and column IDs. componentDidMount() { let board = []; for(let i = 0; i < 30; i++){ for(let j = ...

Ways to decrease and transform a collection of objects?

What is the best way to condense and transform this object array into a new array? Here is the data I am working with: var objArray = [{ state: 'NY', type: 'A', population: 100 }, { state: 'NY', ty ...