Three.js experiencing issues with its Raycaster functionality

Currently, I'm working on a game where players navigate in a first-person view over dynamically generated uneven terrain using Perlin noise. To make the experience more realistic, I aim to incorporate gravity into the gameplay. For this purpose, I've implemented a raycasting mechanism to calculate the distance between the player and the ground, preventing them from falling through it. Below is the code snippet (for a clearer view, please visit ):

const scene = new THREE.Scene(), camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000000000000), renderer = new THREE.WebGLRenderer(), canvas = renderer.domElement; 

camera.rotation.order = "YXZ";

renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMapType = THREE.PCFSoftShadowMap;

document.body.appendChild(canvas);

// Remaining JS code goes here

onkeydown = (event) => {
    if (event.key == "w") camera.translateZ(-10); 
    if (event.key == "a") camera.translateX(-1); 
    if (event.key == "s") camera.translateZ(1); 
    if (event.key == "d") camera.translateX(1); 
    if (event.key == "ArrowUp") camera.translateY(1); 
    if (event.key == "ArrowDown") camera.translateY(-1); 
}
<meta name="viewport" content="width=device-width">
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/94/three.min.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/0949e59f/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/0949e59f/examples/js/utils/SceneUtils.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/0949e59f/examples/js/libs/dat.gui.min.js"></script>

In certain cases, despite being above the ground, the raycasting fails to detect it at least 3 units below the camera level, leading to an issue where the player keeps falling when they shouldn't. This is quite frustrating. Are there any better alternatives to handle this scenario instead of relying solely on raycasting? Could there be a bug in the existing code causing this problem? Thanks in advance!

Answer №1

For detailed information on the Raycaster object, please refer to the official documentation. This method requires providing the starting point, the direction, and specific near and far parameters. For example:

const direction = new THREE.Vector3(0, -1, 0);
raycast = new THREE.Raycaster(camera.position, direction, 0, 3);

In this scenario, specifying the far value eliminates the need for an additional distance check as hits beyond the designated range of 3 units will be automatically excluded.

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

Issue: Anticipated the primary reducer to be a function, but was presented with: 'undefined' in Vanilla JS with Redux

Exploring the world of Redux, I decided to try out some code from a tutorial on YouTube. Building a simple Vanilla JS App, I integrated Redux into it. However, upon running the app in the terminal, an error message popped up saying: "Error: Expected the ro ...

Ways to determine the success of $wpdb->query and retrieve the outcome

Currently, I am in the process of developing a WordPress website, I have implemented a form that allows users to make modifications and update the database: Below is the HTML/PHP code snippet: echo '<form class="form-verifdoc" target=&q ...

ReactJS: streamlining collection method calls using re-base helper functions

I have been struggling to find a way to integrate ReactJS with firebase. Fortunately, I came across the amazing re-base repository which perfectly fits my needs. fb-config.js var Rebase = require('re-base'); var base = Rebase.createClass({ ...

Is it possible to create an animation in NextJS using framer-motion that triggers only during the initial page load and resets every 12 hours?

My website has a main page that loads in with an exciting framer-motion animation. I'm trying to figure out how to make sure this animation only plays the first time the page is loaded, and not every time the page is refreshed or navigated back to. Si ...

Is it possible to alter CSS based on the width of the webpage using javascript

We are currently developing a web application that will be deployed on various devices such as mobile phones, iPads, iPhones, and Android. Instead of using user agents to show different views, I prefer having CSS that adjusts based on the screen width. We ...

Is it possible to spin a background or skybox in three.js?

I'm looking to accomplish a specific rotation of the background on either the x, y, or z axes. How can I achieve this? There is no built-in rotation axis property for scene.background. When creating a box, only the exterior images are visible while ...

Manipulate your table data with jQuery: add, update, delete, and display information with ease

When adding data dynamically to the table and attempting to edit, the checkbox value is not updating. This issue needs to be resolved. You can view the code in action on jsFiddle here on JSFiddle ...

When I click the button, the page goes blank and keeps loading endlessly

http://jsfiddle.net/iansan5653/7EPjH/17/ <head> <script type='text/javascript' src='https://www.google.com/jsapi'></script> <script type="text/javascript"> function chart() { var pressure; ...

Unable to adjust offset/repeat of texture being utilized as alphaMap

demo: the alphaTexture is being modified in its offset with each render. When used as a "map" property, the offset changes, but when used as an "alphaMap" it remains static. This issue arises with the second mesh's alphaMap. relevant code from demo ...

Fetch data using Ajax without the need for a hash signal

My current goal is to load content through Ajax on a website. Let's say our main page is example.com/blankpage (I've eliminated the .html extension using htaccess). At the moment, I have it set up so that when a link on the page directs to mysite ...

Issue with Laravel - JavaScript not functioning properly following the passage of a parameter through the route

I am currently working on a website that will display search results from various e-marketplaces. Everything was going smoothly with the JavaScript implementation until I attempted to pass parameters through the route. Once I did that, the results stopped ...

Obtain the alternative attribute value from the adjacent element and save it to a variable using jQuery

I'm a beginner with jquery and am trying my hand at creating a simple drag and drop game using the following HTML structure: <div class="set-text"> <div class="text">cinema</div> <div class="text">post-office</div> ...

Applying custom CSS to individual divs based on their text height using jQuery

I have a grid consisting of multiple boxes each sized at 280px by 280px, and I am seeking a way to vertically align text within hover overlays on each box. While my current code successfully aligns the text for the first box, I am encountering issues due ...

The ajaxStart() and ajaxStop() methods are not being triggered

I'm currently working on a Q/A platform where users can click on specific questions to be redirected to a page dedicated for answers. However, when a user tries to answer a question by clicking the "Answer" link, certain background processes such as ...

How can I keep the cursor in place while editing a phone number field on Sencha ExtJS?

After one backspace move, the cursor on the phone number field automatically moves to the end which can be inconvenient if the user only wants to edit the area code. Unfortunately, I am unable to post images at the moment due to insufficient reputation. B ...

Ajax call fails to trigger upon change

Currently, I am focusing on creating an HTML table with a form that contains a select element offering options for ALL and Biscuits. Initially, the table populates correctly upon loading. However, I am facing an issue when attempting to trigger an AJAX ca ...

The issue with ng-repeat causing incorrect image width in Flexslider

My webpage features image scrolling functionality, powered by Flexslider. The images on the page are sorted by date - for example, selecting "last 7 days" will display images from the past week (data managed through AngularJS). However, when the JSON dat ...

obtaining pictures from information obtained in vuejs

Trying to showcase images in my code that are already stored in my data like this: <div > <tr v-for='(ships,index) in destroyedShipBox' :key='index'> <td>{{ships}}</td> ...

Create essential CSS for every .html page using Gulp

Recently, I came across a useful npm package recommended by Google for generating critical CSS: var critical = require('critical'); gulp.task('critical', function (cb) { critical.generate({ base: 'app/', ...

Using JQuery to swap out background images in CSS

I have been working on a slider that is supposed to fade one picture over another. The issue is that the background change seems to only work in the Dreamweaver preview and not in the actual browser. loop = setInterval(function(){ $("#slider").css("ba ...