JSONLoader employed for raycasting operations

$(function() {

  /*custom built variables*/
  var scene, camera, renderer;
  var controls, guiControls, datGUI;
  var stats;
  var spotLight, hemi;
  var SCREEN_WIDTH, SCREEN_HEIGHT;
  var mouse, raycaster;
  var objects = [];

  function initialSetup() {
    $(".popup").hide();


    /*creating an empty scene object and renderer*/
    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, .1, 500);
    renderer = new THREE.WebGLRenderer({
      antialias: true
    });

    renderer.setClearColor(0xFFFFFF);
    renderer.setSize(window.innerWidth, window.innerHeight * .8);
    renderer.shadowMap.enabled = false;
    renderer.shadowMapSoft = false;

    

    camera.position.x = 0;
    camera.position.y = 0;
    camera.position.z = 30;
    camera.lookAt(scene.position);


    //adding hemisphere light
    hemi = new THREE.HemisphereLight(0xbbbbbb, 0x660066);
    scene.add(hemi);

    /*adds spot light with initial parameters*/
    spotLight = new THREE.SpotLight(0xffffff);
    spotLight.castShadow = false;
    spotLight.position.set(20, 35, 40);
    scene.add(spotLight);




    var loader = new THREE.JSONLoader();
    loader.load('shreeganeshsweets.in/1.json', function(geometry, materials) {
      var mesh8 = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
      mesh8.translation = THREE.GeometryUtils.center(geometry);
      mesh8.position.x = 0;
      mesh8.position.y = 0;
      mesh8.position.z = 0;
      scene.add(mesh8);
    });

    //adding raycaster and mouse as vectors in 2D
    raycaster = new THREE.Raycaster();
    mouse = new THREE.Vector2();

    //adding event listener for mouse and calling function when activated
    document.addEventListener('mousedown', handleMouseDown, false);
    document.addEventListener('touchstart', handleTouchStart, false);


    $("#webGL-container").append(renderer.domElement);

  }

  function handleTouchStart(event) {

    event.preventDefault();

    event.clientX = event.touches[0].clientX;
    event.clientY = event.touches[0].clientY;
    handleMouseDown(event);

  }

  function handleMouseDown(event) {

    event.preventDefault();

    mouse.x = (event.clientX / renderer.domElement.width) * 2 - 1;
    mouse.y = -(event.clientY / renderer.domElement.height) * 2 + 1;

    raycaster.setFromCamera(mouse, camera);

    var intersects = raycaster.intersectObjects(objects);

    //var color = (Math.random() * 0xffffff);

    if (intersects.length > 0) {

      //intersects[ 0 ].object.material.color.setHex( color );

      this.temp = intersects[0].object.material.color.getHexString();
      this.name = intersects[0].object.name;

      $(".text").empty();
      $(".popup").append("<div class='text'><p>This is the color <strong>#" + this.temp + "</strong> and the name assigned in Blender is <strong>" + this.name + "</strong></p></div>");
      $(".popup").show();

    }

  }

  function renderScene() {

    scene.rotation.y += .001;
  }

  function animateScene() {
    requestAnimationFrame(animateScene);
    renderScene();
    renderer.render(scene, camera);
  }

  initialSetup();
  animateScene();

  $(window).resize(function() {
    SCREEN_WIDTH = window.innerWidth;
    SCREEN_HEIGHT = window.innerHeight;
    camera.aspect = SCREEN_WIDTH / SCREEN_HEIGHT;
    camera.updateProjectionMatrix();
    renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<HTML>
<title>Demo Page</title>
<style>
  body {
    font-family: 'Montserrat', sans-serif;
    margin: 0;
    overflow: hidden;
  }
  .popup {
    height: 100%;
    width: 100%;
    top: 0;
    left: 0;
    color: red;
    background: rgba(1, 1, 0, 0.5);
    position: fixed;
    display: none;
    font-size: 30px;
  }
  .text {
    color: blue;
    background: rgb(1, 1, 1);
    left: 50px;
    top: 20px;
  }
</style>

<body>
  <div class="popup">
    <div class="text"></div>
    <button id="close">&times;close</button>
  </div>
  <div id="webGL-container" style="z-index:-9;"></div>
  <link href='http://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/threejs/r76/three.min.js"></script>
  <script type="text/javascript" src="OrbitControls.js"></script>
  <script type="text/javascript" src="main.js"></script>
</body>

</html>

I am encountering an issue with the raycasting functionality not working as expected in my code setup. I am aiming to have a pop-up appear with predefined information related to the clicked character in the scene. If anyone has insights or solutions regarding this matter, it would be greatly appreciated.

Answer №1

const checkIntersections = raycaster.intersectObjects(objects);

The current objects array does not include the mesh8. Please make sure to add it to the array for accurate intersection detection.

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

JQuery does not allow for changing the selection of a RadioButtonFor

I am currently working on a code that determines whether or not to display contact information. To achieve this, I am using the RadioButtonFor html-helper with a boolean value for the MVC view model in Razor. Upon loading the page, I need to switch from t ...

Wrapping dynamic page titles with comment tags in NextJS for cleaner code

I am currently working on NextJS version 12. In my project, I have a file named Layout.js which contains the following code: import Head from "next/head"; const Layout = ({children, pageTitle, mainClass}) => { return ( <> ...

Creating a dynamic table in AngularJS with rotating values for rows and columns

I am seeking assistance in creating a table with a custom number of rows and columns. The table should have two input fields for specifying the number of rows and columns, and upon submission, the table should dynamically adjust to display the specified nu ...

Convert a string into HTML text using regular expressions

How can you correctly transform a string such as this: html attr = "value" attr2 = 'UnmatchInSubstrings' some \escapedTag content subtag subcontent /subtag br / /html into: <html attr = "value" attr2 = 'UnmatchInSubstrings'&g ...

Utilizing CakePHP 3.0 with jQuery UI for an autocomplete feature

Seeking assistance on why the current code isn't functioning. The objective is to retrieve data from the index controller to search and obtain JSON data. No requests are being made, and there are no visible results. New to CakePHP 3.0, I am attemptin ...

The specified tunnel URL cannot be located (it may still be under preparation), so reverting to the LAN URL

When running expo start, expo r --tunnel, and expo start --tunnel, I encountered the following error: Tunnel URL not found (it might not be ready yet), falling back to LAN URL. Additionally, at times I also face this issue: Error starting tunnel Convertin ...

The issue with importing data into Google Sheets due to an error with Ljava

After combining different scripts, I am struggling to properly input data into the code. Email Input: *Status:* *Date:* 03/31/2020 *WorkOrder:* 123456-1 *DMSShipDate:* 03/31/2020 *PONumber:* 8675309 *Company:* Test New Script var ui = SpreadsheetApp.g ...

Defaulting summernote to display in italics

Looking for a way to italicize a series of summernote inputs by default? I have removed all toolbar options except the italics button. Here's the HTML generating these inputs: <div style="width:250px;"> < ...

Node.js: Manageable simultaneous looping operations

I manage a mongoDB collection containing 1.7 million records, each record representing an ID number. My task involves extracting each ID number, sending requests to another service, performing data transformations, saving the modified data to a separate co ...

Is there a way to serve server-side rendered content exclusively to search engine crawlers like Google Bot, without SSR for regular users in Next.js?

With a staggering number of users visiting the site every day, we are making strides to enhance our visibility on Google by implementing SSR (which may sound unbelievable) and achieving a richer preview when content is shared on messaging platforms. As th ...

The light slider feature is experiencing technical difficulties within the Bootstrap model

I am experiencing an issue with the Light Slider in a Bootstrap modal. Strangely, when I press F12 for inspect element, the Light Slider starts working. For more details and to see the link provided in the comment below, can anyone offer assistance, plea ...

abandoning the upload of an item into a THREE.js environment

Currently, I am working on a THREE.js scene where I need to prevent uploading multiple files into the scene simultaneously. The setup involves using Angular to implement the three js scene and canvas as a factory to maintain only one instance of a canvas a ...

I'm encountering a situation where the displayName is coming up as null during authentication triggers

Why am I receiving null when trying to use user data in the authentication trigger for my code? exports.sendWelcomeMessage = functions.auth.user().onCreate((user) => { const name = user.displayName; console.log(name); return null; }) ...

"Sticky Top Button That Stays in Place When Scrolling | Innovative CSS & jQuery

I've been inspired by the "Proceed to checkout" button on amazon.com and I want to recreate it. However, I'm facing a challenge as their website is not responsive and I can't find a way to view a device user agent in Chrome. To see what I&ap ...

Converting getUserMedia() audio to a .OGG file format using JavaScript

Currently working on an HTML5 project where I am in the process of converting an iOS app to a web-based application. As part of the content creation, there is an audio recording feature that I am trying to replicate using JavaScript without relying on plug ...

The function fails to return a true value

Why is true never returned even when the given name exists in the array rows and the if(rows[i].userName == name) condition is met? function checkIfUserExists(name){ var isUserExists = false; OOTW.MYSQL.query('SELECT * FROM Time',functio ...

Creating a personalized mouse cursor using HTML

I am trying to set an image as my cursor inside a div container but I want it to disappear and revert back to a normal pointer cursor when the mouse hovers over any link within that div. Here is my code snippet: var $box = $(".box"); var $myCursor = $ ...

Storing dynamic field data in React JS: Tips and Tricks

I need help figuring out how to save dynamic field values in a specific format to the database. Here is an example of the format I am looking for: "items": [ { "item_id" : 6, "description" : "", ...

In the realm of programming, the term "is not a function" can be

I've been working on creating an HTML button that triggers a function called switch_user, but when I click it, the console keeps saying that switch_user is not a function. Here's the button in question: <input type="button" class="btn btn-lo ...

How can one access a dynamically generated element in Angular without using querySelector?

Currently in the process of developing my custom toastr service, as shown in the GIF below https://i.sstatic.net/Zpbxs.gif My Objective: https://stackblitz.com/edit/angular-ivy-tgm4st?file=src/app/app.component.ts But without using queryselector. It&apos ...