Implementing a javascript health bar in sugarcube

+1 vote
asked Jun 25 by lululemon (210 points)

I want to make a health bar, that responds to a twine variable $vit[0].

I'm using the javascript:

<progress id="energy" value="$vit[0]" max="100"></progress>

The bar has a value of 0 when used in the story, despite a value of 90 for $vit[0]. Could anyone help with this? 

1 Answer

+1 vote
answered Jun 25 by greyelf (43,790 points)
selected Jun 27 by lululemon
 
Best answer

There are a number of existing threads on the Twine Forum which explain possible methods that can be used to display and update a 'bar' in SugarCube:

a. Health bar in right side bar or in a status passage

b. Live Countdown Bar

I suggest reading the whole of each thread before using either solutions, both of those solutions can be modified to work with a progress element instead.

 

Break down of why your existing example does not work:

The bar has a value of 0 when used in the story

Actually if you use your web-browser's Developer Tools to Inspect the HTML being generated for the progress element in your Passage you will see that has a value of $vit[0] which is invalid so the bar is defaulting to zero.

There are two main issues with your example:

1. When the Passage content is processed the $vit[0] reference is not being substitute with the current value of that variable. There are a number of methods that can be used to get around this issue, the simplest is to use a <<print>> macro to dynamically create the progress element.

<<print '<progress id="energy" value="' + $vit[0] + '" max="100"></progress>'>>

2. You are incorrectly assuming that HTML elements know how to monitor state changes in TwineScript variables, and the simple fact is that they don't. This is why both of the possible solutions I linked to use a SugarCube Task Object to (check the current state and) update the bar manually using Javascript.

Welcome to Twine Q&A, where you can ask questions and receive answers from other members of the community.

You can also find hints and information on Twine on the official wiki and the old forums archive.

See a spam question? Flag it instead of downvoting. A question flagged enough times will automatically be hidden while moderators review it.
...