Javascript coding for monitoring health status using a three.js health bar

After updating to version r127, my health bar stopped working. I'm not sure what changes I need to make to get it working again. There seems to be an error with the shader in this version. Here is the code:

Code:

import * as THREE from './three/build/three.module.js';

  import {entity} from './entity.js';
  import {math} from './math.js';


  export const health_bar = (() => {
    const _VS = `
  varying vec2 vUV;
  void main() {
    vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
    gl_Position = projectionMatrix * mvPosition;
    vUV = uv;
  }
  `;

    const _PS = `
  uniform vec3 colour;
  uniform float health;
  varying vec2 vUV;
  out vec4 out_FragColor;
  void main() {
    out_FragColor = vec4(mix(colour, vec3(0.0), step(health, vUV.y)), 1.0);
  }
  `;

  class HealthBar extends entity.Component {
    constructor(params) {
      super();
      this._params = params;
      this._Initialize();
    }

    _Initialize() {
      const uniforms = {
        colour: {
          value: new THREE.Color( 0xff0000 ),
        },
        health: {
          value: 1.0,
        },
      };
      this._material = new THREE.ShaderMaterial( {
         uniforms: uniforms,
        vertexShader: _VS,
        fragmentShader: _PS,
        blending: THREE.NormalBlending,
        transparent: true,
        depthTest: false,
        depthWrite: false,
        side: THREE.DoubleSide,
      });

      this._geometry = new THREE.BufferGeometry();

      this._bar = new THREE.Mesh(this._geometry, this._material);
      this._bar.frustumCulled = false;
      this._bar.scale.set(2, 0.125, 1);

      this._realHealth = 1.0;
      this._animHealth = 1.0;

      this._params.parent.add(this._bar);
      this._GenerateBuffers();
    }

    InitComponent() {
      this._RegisterHandler('health.update', (m) => { this._OnHealth(m); });
    }

    _OnHealth(msg) {
      const healthPercent = (msg.health / msg.maxHealth);
      
      this._realHealth = healthPercent;
    }

    Update(timeElapsed) {
      const t = 1.0 - Math.pow(0.001, timeElapsed);

      this._animHealth = math.lerp(t, this._animHealth, this._realHealth);

      const _R = new THREE.Color(1.0, 0, 0);
      const _G = new THREE.Color(0.0, 1.0, 0.0);
      const c = _R.clone();
      c.lerpHSL(_G, this._animHealth);

      this._material.uniforms.health.value = this._animHealth;
      this._material.uniforms.colour.value = c;
      this._bar.position.copy(this._parent._position);
      this._bar.position.y += 8.0;
      this._bar.quaternion.copy(this._params.camera.quaternion);
    }

    _GenerateBuffers() {
      const indices = [];
      const positions = [];
      const uvs = [];

      const square = [0, 1, 2, 2, 3, 0];

      indices.push(...square);

      const p1 = new THREE.Vector3(-1, -1, 0);
      const p2 = new THREE.Vector3(-1, 1, 0);
      const p3 = new THREE.Vector3(1, 1, 0);
      const p4 = new THREE.Vector3(1, -1, 0);

      uvs.push(0.0, 0.0);
      uvs.push(1.0, 0.0);
      uvs.push(1.0, 1.0);
      uvs.push(0.0, 1.0);

      positions.push(p1.x, p1.y, p1.z);
      positions.push(p2.x, p2.y, p2.z);
      positions.push(p3.x, p3.y, p3.z);
      positions.push(p4.x, p4.y, p4.z);

      this._geometry.setAttribute(
          'position', new THREE.Float32BufferAttribute(positions, 3));
      this._geometry.setAttribute(
          'uv', new THREE.Float32BufferAttribute(uvs, 2));
      this._geometry.setIndex(
          new THREE.BufferAttribute(new Uint32Array(indices), 1));

      this._geometry.attributes.position.needsUpdate = true;
    }
  };

    return {
      HealthBar: HealthBar,
    };
  })();
  

And here is the shader error:

There seems to be a shader error in the WebGLProgram: shader error: 0 35715 false gl.getProgramInfoLog. It mentions 'pc_fragColor' and 'out_FragColor'. Any help resolving this issue would be greatly appreciated.

Thank you!

Answer №1

It appears that the issue lies with out vec4 out_FragColor;.

out vec4 out_FragColor;
void main() {
  out_FragColor = vec4(mix(colour, vec3(0.0), step(health, vUV.y)), 1.0);
}

Instead of using out vec4 out_FragColor, consider utilizing the default gl_FragColor. Three.js makes it convenient when working with a ShaderMaterial, as it handles the fragment output automatically without needing to be overridden.

// out vec4 out_FragColor; <- This line can be removed
void main() {
  gl_FragColor= vec4(mix(colour, vec3(0.0), step(health, vUV.y)), 1.0);
}

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

While everything ran smoothly on my local machine, the app crashed on Heroku as soon as I integrated express-handlebars into the

After adding this code to the app, it started crashing on Heroku servers. Interestingly, removing these codes resolved the issue and the app worked perfectly on Heroku. However, the app works fine with these codes when tested locally. const exphbs = req ...

Variations between objects?

There are two different methods for using objects in programming. I am curious to understand if the difference lies in the syntax or if there is more to it. Method 1 body(data) = { item1: data.val1; item2: data.val2; item3: data.val3; } Meth ...

You must use the 'new' keyword in order to invoke the class constructor

Although similar questions have been asked before, my situation differs from the typical scenarios. I have a basic base class named CObject structured as follows: export class CObject extends BaseObject { constructor() { super(); } sta ...

Node.js: Calculating the number of requests processed per second in the http.get()

In my node.js project, I am creating a simple application for sending HTTP requests. var http = require('http'); var options = { host: 'www.example.com', port: 80, path: '/index.html' }; for(var i = 0; i < 500; i++ ...

Strategies to avoid red squiggle lines in a contenteditable div that has lost focus

While the div is focused, spell checking is enabled which works well. However, once the focus is removed and there are spelling mistakes, the red squiggle lines for spell checking remain visible. After following the advice provided in this query: spellch ...

In TypeScript version 2.4.1, the fontWeight property encounters an error where a value of type 'number' cannot be assigned to the types of '"inherit", 400'

When attempting to set the fontWeight property in TypeScript, I encounter the following error: Types of property 'test' are incompatible. Type '{ fontWeight: number; }' is not assignable to type 'Partial<CSSProperties>&a ...

Leveraging Json data in Angular components through parsing

I am currently developing an angular application where I need to retrieve and process data from JSON in two different steps. To start, I have a JSON structure that is alphabetically sorted as follows: { "1": "Andy", "2": &qu ...

having difficulty iterating through the data using map function

When attempting to use the map function in React Material UI to display an array of data in a select box, I encountered the error TypeError: Cannot read properties of undefined (reading 'map') while using the following code. Can anyone help me id ...

What is the equivalent of {...props} in React for destructuring props in Vue?

When working in React, I can destructure props with ease: function MyComponent() { const myProp = { cx: '50%', cy: '50%', r: '45%', 'stroke-width': '10%' } return ( <svg> ...

Make the mp3 file automatically download/save as by forcing the link

My website has links to mp3 files using normal <a href="file.mp3"> tags. However, many users with Apple Quicktime installed experience the mp3 files opening instead of saving when clicking on the links. Is there a way to force the browser to save t ...

Tips for fading the text of list items when their checkbox is marked as done?

I am trying to figure out how to gray out a list item when its checkbox is checked. The code I currently have takes text input from a textbox and adds it to an unordered list when the add button is clicked. Each list item contains a checkbox within it. My ...

I'm looking for a streamlined method to simultaneously access multiple APIs with GraphQL and React

For my client side project, I'm using GraphQL and React but opting not to use Redux for state management. Instead, I have organized my API calls into custom hook files as shown below: const [getSomeData, { data: getSomeDataData, loading: getSomeData ...

Navigating multiple navmeshes in Patrol.JS: Tips and tricks

I am currently using patrol.js for navigation purposes. I have successfully managed to navigate on one navmesh. However, I am now faced with the challenge of navigating from one navmesh to another. Is it possible to achieve this transition seamlessly? Here ...

Ways to display a different div when clicking on a div?

Good afternoon, I've noticed that this question has been asked numerous times before, but none of the solutions provided seem to work for my specific issue. My problem involves a div with the class .title3. I want another div with the class .Content ...

Is it possible to remove individual items from a FlatList by clicking on them and updating the state?

I have a FlatList displaying items from an array called data. My goal is to remove each item individually by clicking on it, but currently when I click on one item, all items are deleted at once. Any suggestions on how to address this issue? Here's ...

Sharing a Promise between Two Service Calls within Angular

Currently, I am making a service call to the backend to save an object and expecting a number to be returned via a promise. Here is how the call looks: saveTcTemplate(item: ITermsConditionsTemplate): ng.IPromise<number> { item.modifiedDa ...

Angular2 - Error: The view has been destroyed and cannot be updated: detectChanges

My application keeps encountering this persistent error: extensions::uncaught_exception_handler:8 Error in event handler for runtime.onMessage: Attempt to use a destroyed view: detectChanges at ViewDestroyedException.BaseException [as constructor] (chrome ...

Next.js has shifted away from pre-generating page HTML

I have been working on a Jamstack application using Next.js, and I recently realized that the pages stopped pre-generating the HTML content without me noticing it at first. The pages still load fine, but there is no pre-generated HTML. Even the simplest c ...

Unravel intricate JSON data and display it in a Material-UI table

How to convert the complex JSON data provided below into a material-ui table similar to the example shown. Each row may contain either a single value or multiple rows in a single box. I have attempted to display the data in 2 columns only, but need help wi ...

How can you determine the number of elements that match in two arrays?

As a coding newbie, I'm looking to create a JavaScript function that compares two arrays and assigns a score based on the number of matching elements. However, when I attempt to run it in Chrome's console, I receive an error message stating that ...