Exploring Three.js and managing collisions

I'm currently developing a 3D space shooter game using ThreeJs and facing some challenges with collisions. While I've come across several examples online on how to detect collisions, none seem to solve my specific issue.

The problem arises when the ship collides with a planet and stops moving. However, if the player rotates the ship after the collision and then tries moving forward again, the ship ends up getting "sucked" into the planet!

Check out my demo here: Controls: W,A,S,D to rotate the ship up, left, down, right, respectively. Controls: Up, Down, Left, Right to move and turn.

Below is the specific code snippet that handles collision detection:

function CollisionDetected()
{
    if (!shipSphere)
    {
        return false;
    }

    var moveDistance = 100 * delta; // 100 pixels per second
    var originPoint = shipSphere.position.clone();

    if (shipSphere)
    {
        shipSphere.position.x = ship.position.x;
        shipSphere.position.y = ship.position.y;
        shipSphere.position.z = ship.position.z;

        shipSphere.rotation.x = ship.rotation.x;
        shipSphere.rotation.y = ship.rotation.y;
        shipSphere.rotation.z = ship.rotation.z;
    }


    for (var vertexIndex = 0; vertexIndex < shipSphere.geometry.vertices.length; vertexIndex++)
    {
        var localVertex = shipSphere.geometry.vertices[vertexIndex].clone();
        var globalVertex = localVertex.applyMatrix4(shipSphere.matrix);
        var directionVector = globalVertex.sub(shipSphere.position);

        var ray = new THREE.Raycaster(originPoint, directionVector.clone().normalize());
        var collisionResults = ray.intersectObjects(collidableMeshList);
        if (collisionResults.length > 0 && collisionResults[0].distance < directionVector.length())
        {
            if (keyboard.pressed("up"))
            {
                ship.translateX(-moveDistance*2);
            }
            else if (keyboard.pressed("down"))
            {
                ship.translateX(moveDistance*2);
            }

        }
    }

}

Answer №1

When rotating your ship, ensure that none of the vertices of your sphere intersect with the mesh. This could cause your collision code to be triggered inaccurately, leading to your object moving in the wrong direction.

Instead of rotating the collision sphere along with your ship, try keeping its orientation constant and only rotate the ship itself. This may prevent accidental intersections during rotation.

I've personally used a cube as a collision object in a similar scenario, and it worked well for me.

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

Converting Cookies to Numeric Values in JavaScript: A Step-by-Step Guide

I'm currently developing a cookie clicker website and am encountering an issue with saving the user's score to localstorage when they click the "save" button. Here is what my code looks like: let score = 0; function addPoint() { score += 1; } ...

What is the process for dynamically setting @click in vue.js?

My array contains objects with methods as actions from a vue object. How can I dynamically set the @click event in a v-for loop? I attempted to use this.m1, "this.m1", "m1", but encountered an error: fns.apply is not a function. Javascript: new Vue ...

Prevent JSON.parse() function from stripping away any trailing zeros in a JSON string dataset

After creating a JSON string, I encountered an issue where the values were not being parsed correctly. Here is the code snippet: <script> var string = JSON.parse('{"items":[{"data":[5.1]}, {"values":[5.10]}, {"offer":[3.100]}, {"grandtotal":[12 ...

Saving JSON data as a file on server

Currently, I am running a localhost website on my Raspberry Pi using Apache and I am seeking advice on how to export a JSON string to a file on the Raspberry Pi itself. While I do know how to export a file, I am unsure of how to send it to the Raspberry Pi ...

How can I execute a command line utility using JavaScript?

In my latest project, I am developing a JavaScript tool that requires parsing of a password file ('ypcat passwd | grep ') in a Unix environment. Typically in PERL, this can be done using the "backtick" or System to execute command line operations ...

Guide on adding HTML to an array every third time for displaying

Is there a way to generate div elements every 3 times in a for loop without outputting them as HTML? Any suggestions on how to achieve this? render() { const squareItems = []; for (var i=0; i < 9; i++) { if ((i % 3) == 0){ ...

What is the best way to invoke a Servlet from within a d3.json() function

Currently, I am using d3 to create charts with nodes and links connecting them. In order to retrieve the data, I have used a json file named link.json and accessed it using the following code: d3.json("link.json", function(error, graph) {} Although this ...

The variable fails to receive a value due to an issue with AJAX functionality

I am struggling to figure out what's causing an issue with my code. I need to store the result of an AJAX request in a variable, specifically an image URL that I want to preload. $.ajax({ type: "POST", url: 'code/submit/submi ...

``The presence of symlink leading to the existence of two different versions of React

Currently, I am working on a project that involves various sub custom npm modules loaded in. We usually work within these submodules, then publish them to a private npm repository and finally pull them into the main platform of the project for use. In orde ...

Encountering a module not found error while compiling in Visual Studio

My TypeScript app compiles successfully using webpack, but I encountered an error "Build: Cannot find module 'react'" when attempting to build it in Visual Studio. Any assistance would be greatly appreciated. Here is my package.json: { "nam ...

How to change the state using an object as an argument in the useState hook within a function

This code uses a function component: export default function Account() { We define a constant with inputs as objects: const [state, setState] = useState({ profile: true, orders: false, returns: false, coupon: false, referrals: false, rewards: ...

What is the best way to create a delay so that it only appears after 16 seconds have elapsed?

Is there a way to delay the appearance of the sliding box until 16 seconds have passed? <script type="text/javascript"> $(function() { $(window).scroll(function(){ var distanceTop = $('#last').offset().top - $(window).height(); ...

Best practice for organizing sort icons in a table with React and MaterialUI

I am currently implementing the following code in a tsx component. I am still learning about the various layout options available. You can view my code on this sandbox link. import React from "react"; import { ArrowDropUp, ArrowDropDown } from "@materia ...

Issue with implementing autocomplete using AJAX and PHP for multiple input fields

HTML code: <table> <tr> <td align="center"> <label for="InputBox1"><b>~</b><font color="red">*</font>: &nbsp;</label> </td> </tr> <tr> <td align="center"> <div id="1"> ...

Unexpected outcomes when using three.js getWorldPosition method

Please check out the gist I put together over at https://gist.github.com/sparkbuzz/f1f8d0d8bbc7757b679f In this gist, you'll find a TypeScript class named OrbitControls. I've been delving into 3D and three.js to explore creating orbit-style con ...

Navigating through Object Arrays in JavaScript

I am relatively new to learning Javascript and could use some assistance with the code snippet shared below which is from Eloquent Javascript. var journal = []; function addEntry(events, didITurnIntoASquirrel) { journal.push({ events: events, squ ...

jQuery replacement for replaceChild method

I've been attempting to swap out an existing DOM element with a new one that I created. I attempted the following code snippet: $(this).parent().replaceChild(newElem,this); However, it resulted in an error message saying $(this).parent().replaceChi ...

Is there a way to determine if a component has a binding on a directive?

I am in need of assistance regarding a directive named my-custom-directive. Here is how I am currently implementing it: <my-component v-model="things.value" v-bind:error="things.error" v-my-custom-directive> </my-component> Within ...

Odd behavior observed when clicking on the link

On the initial click with an anchor tag, I am experiencing different behavior compared to subsequent clicks. When the href value is set to "", no HTTP GET request is made on the first click. I cannot determine why the first click would behave differently t ...

The issue of data binding failure in AngularJS is frustrating as it prevents the entered values from appearing within the controller's scope variables

I am encountering an unusual issue where the binding of $scope variables does not seem to be functioning as expected. Below is the HTML code: <div class="input-group" style="width:100px"> <input type="number" ...