Jump to content

TypeScript, global functions for use in every state


BdR
 Share

Recommended Posts

I'm working on a game using Phaser and TypeScript, and I want to call the same function from several different states.
It is a fade-out function to fade the entire screen to black, which I want to use in both my MainMenu, LevelSelect and Game states (and btw I also want a global function that starts/stops the music).

I know globals are considered a Bad Thingtm, but my question is; how can I create a function that can be re-used by all states?

I've tried adding the global variables and functions in my boot state, like so

module MyGameProj.Client {
    var SOUND_IS_ON = true;
    var MUSIC_IS_ON = true;
    
    function switchMusic(game, onoff) {
        MUSIC_IS_ON = onoff;
        // .. etc.
    }

    export class Boot extends Phaser.State {
        preload() {
            switchMusic(this.game, true); // no errors
            //.. etc.

But then when I try to access the switchMusic from my MainMenu state, it gives an error 'Cannot find name switchMusic'. However, they can be used and called from within the Boot state.

module MyGameProj.Client {
    
    export class MainMenu extends Phaser.State {
        create() {
            switchMusic(this.game, true); // <- error; Cannot find name switchMusic
            //.. etc.

(btw there is no option for TypeScript in the code snippets)
 

Link to comment
Share on other sites

Hi, try to add "export" before your function. Instead of single global function, you can create object with static methods to group these at one place.

Or for this you can extend Phaser.Game class (call it let's say MyGame) and have some methods needed across game in it. "game" object is part of any state, so you can then cast it up to your game class like: (<MyGame>this.game).doSomething();

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...