Detecting collision between two moving objects in Three.js with the use of a Ray

I am currently working on developing a 3D breakout game using THREE.js and WebGL rendering technology. My goal is to utilize THREE.Ray to detect collisions between the bouncing ball and the controllable platform at the bottom. However, I am encountering some difficulties.

While I have successfully cast a ray from the platform to the ball (or vice versa), the ball ends up getting stuck in the middle of the screen and is unable to be animated.

var ray = new THREE.Ray( platform.position, ball.position.subSelf( platform.position ).normalize() );
var intersects = ray.intersectObject( ball );

if ( intersects.length > 0 ) console.log(intersects[0].distance);

I have attempted to remove the subSelf and normalize() functions, but this results in the collision detection breaking.

The game and code can be accessed in the script.js file:

By opening the console, you can observe that the distance value changes as you move the panel, which is a positive sign. However, the ball is unable to move due to it being set to the same position in every frame.

The original method involved calculating the Z position of the ball and platform, checking if it's within the panel's width (x) coordinates, and changing its direction accordingly.

For ball bouncing, the X and Z coordinates are modified by a fixed amount each frame. If it exceeds a certain limit, the direction is reversed to maintain movement within the game boundaries.

Answer №1

Through some experimentation, I was able to figure it out.

let ray = new THREE.Ray(ball.position, new THREE.Vector3(ball.position.x, ball.position.y, platform.position.z).subSelf(ball.position).normalize());

let intersects = ray.intersectObject(platform);

if (intersects.length > 0) {

    let face = intersects[0].face.d,
    distance = intersects[0].distance;

    if (face === 4 && distance <= 7) {
        sizes.ball.velocityZ = -sizes.ball.velocityZ;
    }

};

Essentially, by constantly projecting a ray downward from the ball and checking if the platform is directly beneath it within a certain distance, I can reverse the ball's direction as needed.

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

Which type of element does Youtube utilize for the videos on its own domain - <iframe> or <video>?

Do they have a different method for incorporating their videos? My goal is to utilize the playbackRate property on a non-embedded YouTube video for a Chrome extension. ...

Is there a way for me to keep an image stationary on the page while allowing overlaying text to move?

Currently, I am exploring the process of coding a website that mimics the style of this particular webpage: . I am particularly interested in learning how to create a scrolling effect for text within a fixed area, while keeping the accompanying images st ...

Angular 6 - Using properties in classes

Considering a component structured as follows: import { Component, OnInit, ViewChild } from '@angular/core'; @Component({ selector: '...', templateUrl: './...html', styleUrls: ['./...scss'] }) export class Te ...

Organize the array object by roles using mapping and grouping techniques

Given an object array with roles as keys and values, I want to group them according to the roles assigned. Here is the sample data: { users: [ { firstName: 'Will', lastName: 'Jacob', email: '<a href="/cd ...

Responsive Design: Concealing a Sidebar with CSS

Seeking assistance with optimizing the layout of my app, . It currently displays a menu on the left and a login form in the center, with a graph shown to users upon logging in. Is there a way to configure it so that when accessed on iOS: 1) the left menu ...

Encountering Type Error in Angular 2

Here is the Angular 2 code snippet I am working with: <ion-grid *ngFor="let item of menuData; let i = index;" ng-init="getAllItemToGrid()"> <img src="{{'assets/Products/'+menuData[i].image}}" ng-click="onLogin()" width="100%"> ...

Issues with Navigating through a Scrollable Menu

I'm having a difficult time grasping the concept and implementing a functional scrolling mechanism. Objective: Develop a large image viewer/gallery where users can navigate through images by clicking arrow keys or thumbnails in a menu. The gallery an ...

Navigating a collection of objects in JavaScript: A step-by-step guide

My data consists of objects in an array with the following structure: [{\"user\":\"mcnewsmcfc\",\"num\":11},{\"user\":\"ManCityFNH\",\"num\":7}]; To clean up the array, I'm using this code: ...

Unable to retrieve data from the React API

Whenever I try to reload my page, I encounter an error while fetching content from the API. I have attached an image showing the issue. My goal is to retrieve weather details using the Weather API, and for now, I am using fixed latitude and longitude value ...

Ways to designate ROLES within the _user database on Cloudant

I am struggling to figure out how to add Roles to users in the Cloudant user database (_users). Despite searching through Google and Cloudant Docs, I have not been able to find a solution. There is mention of a Cloudant _user db, but I can't seem to u ...

The 'onChange' event in React is being triggered only once

Currently utilizing material-ui Library Below is my React component: import Checkbox from '@material-ui/core/Checkbox'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import React from "react"; import { withStyles ...

How can we enable a sitemap for web crawlers in a nodejs/express application?

Looking to enable sitemap for web crawlers in nodejs/express? I am trying to figure out where I should place my sitemap folder/files within the application flow and how to allow access for web crawlers. Currently, when visiting domain/sitemap/sitemap.xml, ...

Exporting JSON data from Blender for use in Three.js

Whenever I try to export some obj models from Blender to json using the three.js plugin, it always seems to result in javascript errors on my web page. The specific error message that pops up is: TypeError: vertices is undefined This error occurs at th ...

Stopping repetitive ajax requests

When I click the "load more" button quickly, it ends up loading the same content twice. I'm looking for a way to prevent this from happening. Below is the ajax call I use to load more content: <script type="text/javascript"> function loadmor ...

An issue occurred with the DOMException while trying to execute the 'setAttribute' function on the 'Element': '{{' is an invalid attribute identifier

Currently, the code is under development and some methods are still empty while the *ngIf directives may not be correct in terms of logic. However, even with these issues, I encountered the same error without bothering to remove them at this stage. While ...

Creating client side scripts for an ajax call to generate a Json object is simple once you understand the basics

Typically, when I make ajax calls, I request pure HTML. However, for various reasons, I require guidance on constructing a table (let's say of individuals and their information) when receiving a Json object. While I am capable of creating a table in J ...

Encountering a Zone.js error when trying to load an Angular 7 app using ng serve, preventing the application from loading

Scenario: Yesterday, I decided to upgrade my Angular app from version 5.2.9 to 6 and thought it would be a good idea to go all the way to 7 while I was at it. It ended up taking the whole day and required numerous changes to multiple files, mostly due to R ...

Open the overflow div within a table data cell

My goal is to create a drag-and-drop schedule tool similar to Fullcalendar. I have decided to use a table layout with a rectangular div inside each TD cell to represent tasks. <table onDragEnd={dragend}> <tr> <th>0</th> ...

Utilizing React Native to Query, Filter, and Save a Single Document Field Value from Firestore Database into a Variable/Constant

My current task involves setting up a Firebase Firestore Database in order to filter it based on a specific field value within a document. The collection I am working with is named "PRD" and consists of thousands of documents, each sharing the same set of ...

Tips for handling an empty jQuery selection

Below is the code snippet: PHP CODE: if($data2_array[7]['status'] == "OK"){ $degtorad = 0.01745329; $radtodeg = 57.29577951; $dlong = ($lng - $supermercado_lng); $dvalue = (sin($lat * $degtorad) * sin($superm ...