Attempting to establish limits for the movement of a three.js cube

I'm currently working on developing a straightforward app that allows me to move a cube either to the left or right. The movement part has been successfully implemented, and now I am faced with the challenge of ensuring that the cube stays within the bounds of the plane. What would be the most efficient way to achieve this?

Here is the code snippet that I have been working on:

<html>
    <head>
        <title>Time Car</title>
        <style>
            body {
                width: 100%;
                height: 100%;
                margin: 0;
                padding 0;
            }
        </style>
    </head>

    <body>
        <script src="js/three.min.js"></script>
        <script src="js/Detector.js"></script>
        <script>
            var scene, camera, renderer, object, raycaster, board1, board2, board3, board4;
            var vy = 0,
                vx = 0,
                direction = "",
                gravity = 0.3;


            function init() {

                if (!Detector.webgl) Detector.addGetWebGLMessage();

                scene = new THREE.Scene();

                camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

                renderer = new THREE.WebGLRenderer({
                    antialias: true
                });
                renderer.setSize(window.innerWidth, window.innerHeight);
                renderer.setClearColor(0xCCFFFF);

                document.body.appendChild(renderer.domElement);

                var light = new THREE.DirectionalLight(0xffffff, 2);
                light.position.set(1, 1, 1).normalize();
                scene.add(light);

                var light = new THREE.DirectionalLight(0xffffff);
                light.position.set(-1, -1, -1).normalize();
                scene.add(light);

                var geometry = new THREE.BoxGeometry(20, 10, 10);
                object = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
                    color: 0x3333FF
                }));
                scene.add(object);

                var geometry = new THREE.PlaneGeometry(5000, 800, 800);
                var plane = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
                    color: 0x99FF66
                }));
                plane.rotation.x = -Math.PI / 2;
                plane.position.set(0, -20, 0);
                scene.add(plane);

                camera.position.set(0, 100, 100);

                raycaster = new THREE.Raycaster();
                raycaster.ray.direction.set(0, -1, 0);

                render();
            }

            function render() {

                requestAnimationFrame(render);

                if (direction == "left") {
                    vx = -2;
                }
                if (direction == "right") {
                    vx = 2;
                }
                object.position.x += vx;
                vx = vx * 0.95;

                camera.lookAt(object.position);
                camera.position.x += (((object.position.x - 20) - camera.position.x)) * 0.03;

                camera.position.y += (((object.position.y + 50) - camera.position.y));

                renderer.render(scene, camera);
            }

            window.addEventListener('keydown', function (e) {
                switch (e.keyCode) {
                case 65: //left
                    direction = "left";
                    break;

                    break;
                case 68: //right
                    direction = "right";
                    break;
                };
            }, false);
            window.addEventListener('keyup', function (e) {
                switch (e.keyCode) {
                case 65: //left
                    direction = "";
                    break;
                case 68: //right
                    direction = "";
                    break;
                };
            }, false);

            init();
        </script>
    </body>
</html>

Answer №1

If I understand correctly, you have configured the plane like this:

geometry = new THREE.PlaneGeometry(5000, 800, 800);
...
plane.position.set(0, -20, 0);

Now we can calculate its bounding box:

plane.geometry.computeBoundingBox();

The plane's size along the x-axis is 5000 and it has not been moved along this axis, so plane.geometry.boundingBox.min.x is -2500 and plane.geometry.boundingBox.max.x is 2500. In your animation loop, you can monitor the position of the object. Here is how you can do that:

object.position.x += vx;
var objHalfWidth = object.geometry.parameters.width / 2;
if (object.position.x + objHalfWidth >= plane.geometry.boundingBox.max.x){
    object.position.x = plane.geometry.boundingBox.max.x - objHalfWidth;
}
if (object.position.x - objHalfWidth <= plane.geometry.boundingBox.min.x){
    object.position.x = plane.geometry.boundingBox.min.x + objHalfWidth;
}

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

Implementing alpha-map with three.js OBJMTL loader

I'm currently attempting to upload these .obj and .mtl files using OBJMTLloader. Everything is working correctly, except for the fact that the image in the mtl file loaded by map_d is not being uploaded. newmtl Eyelashes Ns 10.0000 Ni 1.5000 d 0.50 ...

Encountered an issue while attempting to access the length property of an undefined value when fetching the results of a MYSQL query

For some time now, I've been grappling with a particular problem and while I hate to admit it, I could just be missing something obvious. My current task involves creating a basic system using NodeJS + Express + MYSQL that allows users to easily log i ...

Assign a class to each offspring of a slot

I am currently in the process of setting up a component with a slot that, upon rendering, adds a specific class to each child within that slot. To simplify: <template> <div> <slot name="footerItems"></slot> </div> ...

Angular does not recognize the function element.sortable

I'm attempting to utilize ui.sortable in order to create a sortable list. Despite following the instructions provided at https://github.com/angular-ui/ui-sortable, I am still encountering an issue and receiving the following error message: TypeError: ...

Maintain the expanded menu even after selecting a sub-item using jQuery

After conducting a thorough search, I was unable to find exactly what I needed. I have successfully implemented cookies on my menu so that when the page is reloaded, it remembers which menus were open. However, I noticed that clicking on a sub-item of Hy ...

Display a div in a specific color depending on whether the value is positive or negative, and

I created a counter but I want to change the color of the id="clicks" based on whether the value is positive or negative, and also add text accordingly. var clicks = 0; function clickplus() { clicks += 1; document.getE ...

Scrolling infinitely within the side menu using ion-infinite-scroll

I'm encountering an issue with using Ion-infinite-scroll within ion-side-menu, as the load more function is not being triggered. Is it permitted to utilize ion-infinite-scroll inside ion-side-menu? Although I have added the directive, the method "lo ...

What is the correct method for formatting a JavaScript tag?

As someone who has been developing web apps since 1996, I am constantly exploring new approaches to familiar tasks. This has led me to ponder on the best JavaScript tag to use for my latest projects. Currently, I tend to utilize something like the followi ...

JavaScript error: Cannot read property 'str' of undefined

I'm attempting to retrieve specific values from a JSON array object, but I encounter an error message. var i = 0; while (i < n) { $.get("counter.html").done(function (data2) { var $html = $("<div>").html(data2); var str = ...

What is causing my AJAX Contact Form to navigate away from the original page?

I configured a contact form on my website more than 5 years ago, and I vividly remember that it used to show error/success messages directly on the page within the #form-messages div. However, recently, instead of staying on the contact form page and displ ...

Present a pop-up notification box with a countdown of 30 seconds prior to the expiration of a session timeout in JSF

Our task is to create a timeout window that appears 30 seconds before the session expires. If the user remains inactive, they will be automatically redirected to the home page. We already have the maximum allowed duration of inactivity defined. I would l ...

What's the best way to display a bootstrap modal window popup without redirecting to a new page?

I am having trouble implementing a modal window that will display validation errors to the user when they submit a form. Currently, the window is opening as a new view instead of overlapping the existing form's view. How can I adjust my code so that t ...

Is there a way to search for a specific item within a nested array?

I have 2 arrays within an array, each containing objects. How can I locate the object with the name "Sneijder"? const players = [ [ { id: 1, name: "Hagi", }, { id: 2, name: "Carlos", }, ], [ { id: 3 ...

Guide for configuring a server to exclusively render Vue components

I have been utilizing the vue-no-ssr library (available at https://github.com/egoist/vue-no-ssr), but it only renders components on the client side. I require my component to render on the server side. Is there a method to create a vue component that exclu ...

Tips for efficiently handling MongoDB data on the server side with socket management

My venture into using Socket.io for the first time has led me to create a simple game. At this point, I have a MongoDB database structured as follows: | Sessions | | Users | | Games | |-----------| |------------| |-----------| | * _id | ...

When all y values are zero, Highcharts.js will shift the line to the bottom of the chart

Is there a way to move the 0 line on the y axis to the bottom of the chart when all values are 0? I attempted the solution provided in this post without success. Highcharts: Ensure y-Axis 0 value is at chart bottom http://jsfiddle.net/tZayD/58/ $(functi ...

AJAX Post data transmission on the network: Enhancing data formatting

For my AJAX post call, I need to format the data differently. The server is expecting the data in a specific format when viewed in Chrome Network Headers details. My task is to update the JavaScript code below to meet this formatting requirement: percenta ...

Revise the calculation output when a specific input is missing

As I work on creating a basic web page for computing values based on selected options, I've encountered an issue with the calculation process. The result does not immediately appear; instead, I have to input a value like 0 and then delete it in order ...

What is the best way to reindex dynamically added rows in jQuery?

I've been searching everywhere, but I can't seem to find the solution to my problem. I have a table where rows are dynamically added based on an index. So, when I click on a link in row 5, I want to add a new row at index 6. The issue arises when ...

Issue with nodejs routing: res.redirect causing a 404 error instead of proper redirection

Recently, I started working on a web application using nodejs, express, and mongodb as a beginner. Below is a snippet of my app.js file: var express = require('express'); var path = require('path'); var favicon = require('serve-fa ...