Having trouble with this script

What it is supposed to do is enable entity1 and disable entity2 when the button is clicked, then it sets a timeout where the entity revert back to what state they were in before the button was clicked

<button onclick="toggleEntities()">Toggle Entities</button>

<script>
function toggleEntities() {
  setTimeout(function() {
    // Set the entities back to their original state after 4 seconds
    entity1.setAttribute('disabled', false);
    entity2.setAttribute('disabled', true);
  }, 4000);

  // Enable entity1 and disable entity2
  entity1.setAttribute('disabled', true);
  entity2.setAttribute('disabled', false);
}
</script>

Is this the correct way to do this on playcanvas?

I know how to code in JavaScript but the structure on PlayCanvas seems to be very different from what I learned, and I was hoping someone would please translate my script into a functional piece for PlayCanvas.

Hi @Jacob_McBride1,

Here is an example project on how to do this:
https://playcanvas.com/editor/scene/1615735

I’ve forked the default HTML/CSS UI tutorial and I’ve expanded the ui.js script to accept entity attributes and execute your code (adapted):

image

2 Likes

@Jacob_McBride1 Hi and welcome. Playcanvas is javascript you have probably seen in some of the examples. It is just a different thought process, in some cases, than just web page development. Although there is support for css and all the normal things you may be used to for user screens etc. Here is a quick example from the tutorials on buttons.

User Interface - Buttons | Learn PlayCanvas

Also, you can search this forum for other user related questions

1 Like

Oh My god, this is a lifesaver! Thank you so much!

Is this type of coding acceptable?

// Define the Default object
var Default = function() {
    // The initialize function will be called once when the entity is created
    this.initialize = function() {
        // Set the initial time scale, but only if this.app.time is defined
        if (typeof this.app.time !== "undefined") {
            this.app.time.timeScale = 1;
        }
    };

    // The update function will be called every frame
    this.update = function(dt) {
        // Check if the space key is being held
        if (this.app.keyboard.isPressed(pc.KEY_SPACE)) {
            // Set the time scale to 0.5, but only if this.app.time is defined
            if (typeof this.app.time !== "undefined") {
                this.app.time.timeScale = 0.5;
            }
        } else {
            // Set the time scale to 1, but only if this.app.time is defined
            if (typeof this.app.time !== "undefined") {
                this.app.time.timeScale = 1;
            }
        }
    };
};