Forum Discussion

CajaPopularM704's avatar
CajaPopularM704
Community Member
4 months ago
Solved

Button Listener to move a character

Hello everyone I've dealing with a problem, I started a project, it is supposed to be an Escape Room, and most of the things I need for it are already available on Storyline. But I've been stuck ...
  • Nedim's avatar
    4 months ago

    There are a few issues here. First, the object returned by the newer JavaScript API (e.g., object('5yfHufFxicy')) does not reference the actual DOM element. It only exposes a limited set of properties and methods, so you can’t attach event listeners to it directly.

    A more appropriate way to target the real DOM element would be using attributes like data-model-id or data-acc-text. However, in this case, that approach isn't necessary.

    Since we already have a Storyline trigger that runs when the button state is Down, we can use that to handle the action (e.g., movement) instead of relying on event listeners. This makes the setup simpler and more reliable, as we can focus entirely on controlling the character's movement through Storyline logic and variable-based triggers.

    In the updated file, there are now two buttons (Left and Right) that move the character in the corresponding direction when their state is set to Down. To keep the logic consistent, I created two Boolean variables: isLeftPressed and isRightPressed. These variables track whether the character should move left or right.

    When neither button is in the Down state, the character’s movement is paused. As soon as either button is pressed again, the movement resumes in the appropriate direction. 

    Example code executed when the Right button is in the Down state (starts moving the character to the right):

    const character = object('6EPGwyDzEfX');
    
    if (getVar("isRightPressed")) {
    
    	window.characterMoveInterval = setInterval(() => {
    	    const currentX = character.x;
    	    const newX = currentX + 2;
    
        	gsap.set(character, { x: newX });
      	}, 50);
    }

    Stop the character movement when a button is not in Down state:

    clearInterval(window.characterMoveInterval);