How can we limit the camera's movement to a specific area in THREE.js?

I am currently working on a game that involves gravity, and I am facing the challenge of preventing movement when hitting a wall or obstacle. I initially tried just halting forward movement, but then realized players could simply turn around and continue in reverse. Unfortunately, this approach did not work.

Below is the snippet of my movement code:

document.onkeydown = function(e) {
    // e.preventDefault()
    if(e.keyCode == 87) {
        player.movement.w = true
    }
    if(e.keyCode == 65) {
        player.movement.a = true
    }
    if(e.keyCode == 83) {
        player.movement.s = true
    }
    if(e.keyCode == 68) {
        player.movement.d = true
    }
    if(e.keyCode == 69) {
        player.movement.e = true
    }
    if(e.keyCode == 81) {
        player.movement.q = true
    }
}
document.onkeyup = function(e) {
    if(e.keyCode == 87) {
        player.movement.w = false
    }
    if(e.keyCode == 65) {
        player.movement.a = false
    }
    if(e.keyCode == 83) {
        player.movement.s = false
    }
    if(e.keyCode == 68) {
        player.movement.d = false
    }
    if(e.keyCode == 69) {
        player.movement.e = false
    }
    if(e.keyCode == 81) {
        player.movement.q = false
    }
}

function loop() {
requestAnimationFrame(loop)

if(player.look.locked == true) {
        if(player.movement.w == true) {
            playerObj.translateZ(player.movement.speed / 100)
        }
        if(player.movement.a == true) {
            playerObj.translateX(player.movement.speed / 100)
        }
        if(player.movement.s == true) {
            playerObj.translateZ(player.movement.speed / 100 * -1)
        }
        if(player.movement.d == true) {
            playerObj.translateX(player.movement.speed / 100 * -1)
        }
        if(player.movement.e == true) {
            playerObj.translateY(player.movement.speed / 100 * -1)
        }
        if(player.movement.q == true) {
            playerObj.translateY(player.movement.speed / 50)
        }
    }
}
loop()

(I am aware that event.keyCode is deprecated)

Answer №1

When I first attempted to create a 3D game using THREE.js, I quickly realized that my lack of experience with physics made the process much more challenging than expected. In search of a solution, I turned to an alternative approach which unfortunately did not yield the desired results.

My recommendation: Instead of struggling with workarounds, consider utilizing CANNON.js for handling physics in your project. By setting up the camera to follow a box controlled by CANNON.js and adjusting its position based on the box's movement, you can achieve smoother navigation. Implementing collision detection and utilizing various shapes from CANNON.js can also enhance the overall scene creation process.

Interestingly, I encountered a minor issue during my initial exploration of this technique: it's crucial to remember that CANNON.js and THREE.js operate as separate entities, which necessitates combining the two worlds effectively.

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

Adjusting the Three.js camera with device orientation: Unusual results when the device is positioned vertically

In my current project, I am experimenting with three.js and have set up a scenario where the camera is positioned inside a textured sweater. The rotation of the camera is controlled by the orientation of the phone in space. Initially, everything seems to b ...

Adjusting the height of the scrollbar in relation to a div using jScrollPane

I am currently working on a resizable div that utilizes custom scrollbars from jScrollPane. My goal is to position the vertical scrollbar above the resize handle. Is there a way to achieve this? I experimented with adjusting the verticalTrackHeight by al ...

Unlocking the potential of a loaded model using objectLoader

Currently, I am attempting to import an external model using ObjectLoader and have implemented the following code: loader.load( 'teapot.obj', function ( object ) { globalobject=object; object.traverse( function ( child ) { ...

Disabling related videos in React Native: A guide to preventing suggested content from appearing at the end of YouTube videos

Is there a way to turn off the display of related videos after a YouTube video ends in react native? I've tried the following code, but it doesn't seem to be working: state = { isPlaying: true, related :false, }; <YouTube apiKe ...

Previewing materials in three.js allows you to see how different

Currently, I am developing a method to display materials directly within the browser. The idea is to have one or multiple geometries and the ability to select a specific path for loading 3 textures from a local folder onto the geometry. Each folder will c ...

What could be causing the error to occur in the form when I try to submit it?

After creating a page in bootstrap 4, I encountered an issue with the modal. Whenever I click on any input field or button inside the modal, it shows the same error message. I'm quite confused and don't know what's causing this problem. Upon ...

How can jQuery be used to transmit boolean field data from a template to Django views?

Is there a way to use jQuery to send form values from a template to a database? I am looking to change the boolean value in a checkbox and save it in a model, then send this information to the view using jQuery. Within my template, I have the following co ...

Error: The function **now.toUTCString** is not recognized and cannot be executed by HTMLButtonElement

While the JavaScript code runs smoothly without setting a time zone, I encountered an error when trying to display the Barbados time zone. The issue is related to now.toUTCString function throwing the following error message. How can I resolve this? Uncau ...

Detecting collisions in JavaScript

Currently, I am in the process of reviving an old game reminiscent of Tron using HTML5 canvas and JavaScript. The unique twist in this version is that the snakes have the ability to move in curves rather than right angles (known as Achtung Die Kurve). The ...

Storing user input in MongoDB after encoding

I am currently exploring the most effective methods for storing and presenting user input in MongoDB. In traditional SQL databases, it is necessary to encode all user input as a precaution against injection attacks. However, in the context of MongoDB, ther ...

How come the likes are not being refreshed when the button is clicked in my mongoose schema?

I am currently working on an express app using nodejs and mongoose. My main goal is to implement a JavaScript function that can update the number of likes on a post in a database directly from my ejs file. However, I have encountered troubles with this tas ...

Missing Component when Nested within Route in React Router v6

While incorporating the ChoosePlayer component within a Route using React Router v6, <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="/players"> <Route element ...

The typical initial default argument to be passed to the function using fn.apply

Recently, I discovered the power of using fn.apply() in JavaScript to store function calls with all their arguments intact for future use. In my specific situation, I don't require the first argument, which is the context (this), and I want to find a ...

Focus on the image displayed through instafeed.js

Using the Instafeed.js plugin to create a dynamic Instagram feed. Everything is working smoothly, but I'm struggling to center the images being retrieved by Instafeed. Despite trying various methods, I can't seem to get it to display as desired. ...

Exploring the differences between selecting an element by its class and making multiple calls to select elements

I have a question about choosing multiple elements from a page. Is it better to use a selector by class, or make multiple calls using the selector by id? The number of elements I want to select, or unwanted elements that need to be checked by the selector ...

Basic HTML and JavaScript shell game concept

After spending several days working on this project, I am struggling to understand why the winning or losing message is not being displayed. The project involves a simple shell game created using HTML, JavaScript, and CSS. I have tried reworking the JavaSc ...

Challenge with neglected open connections from a comet

Utilizing various comet techniques like long polling and forever frame, along with iframes for cross subdomain activities, has presented a challenge during implementation. When a user refreshes the page or navigates to another page, a new request is made w ...

React is unable to identify the `initialValue` attribute on a DOM element

Warning: React is not able to recognize the `initialValue` property on a DOM element. If you intended for it to show up in the DOM as a custom attribute, use `initialvalue` in lowercase instead. If it was mistakenly passed from a parent component, make sur ...

Ways to verify the presence of an empty array object

I'm trying to determine whether all arrays inside an object are empty. To illustrate, consider the following object: var obj = { arr1: [0, 1, 2], arr2: [1, 2, 3], arr3: [2, 3, 4] }; After pop()ing values from the arrays within the object, I ...

Tips for moving an object on terrain in Three.js while ensuring it aligns with the natural contours

When moving a tank over a bridge in my example, there are two approaches to solve the problem. One is to rely on physics for the Math computations, while the other involves manually calculating the height and rotation values for the vehicle (my preferred a ...