my game loop


My game loop works and I want someone to look at it to see if I can improve it AS3 style.
What I do is load an image from a class and it dispatches an event when completed. When all images are loaded (which is 1 in this example) I then start the game loop which is just a trace.

This way I could load many images and then start the my game loop

This is a skeleton I can build upon.



var noLoaded:int; noLoaded=0 var li:ClassImg2= new ClassImg2("ladybug.png",120,120); li.addEventListener("image_loaded",imageLoadedHandler); addChild(li); function imageLoadedHandler(e:Event){      stage.addEventListener(KeyboardEvent.KEY_DOWN,doSomething);   noLoaded+=1 } function doSomething(e:KeyboardEvent):void      {                      if (e.keyCode==37) //39 is right arrow           {                      trace("left pressed")           li.moveleft();                      }                      if (e.keyCode==39) //39 is right arrow           {                      trace("right pressed")           li.moveright();                      }      }       stage.addEventListener(Event.ENTER_FRAME, gameLoop); function gameLoop(event:Event)      {      if (noLoaded==1)           {           trace("all loaded");                }      }

They are triggered regardless - it's the idea and the beauty of the events. Strictly speaking, because there is no multithreading in Flash - all events in treatment penetrates into the queue of the stack, but most of the time from the performance perspective, it is negligible. That said, your opinion on the control of collisions in the ENTER_FRAME event handler is the way to go.

Tags: Adobe Animate

Similar Questions

  • Multi-threaded in JavaFX game loop

    I am trying to understand works threading model of JavaFX, to determine the best way to write my game loops. This moment, my approach is this:

    EventHandler < ActionEvent > gameUpdate = event->

    {

    update of the world based on a timestep (see below) 33.3ms

    };

    gameLoop = new chronology (new KeyFrame (Duration.millis (33.3), gameUpdate));

    gameLoop.setCycleCount (Animation.INDEFINITE);

    My understanding is that:

    1. This should result in the game loop to run at around 30 FPS (the target frame rate), assuming that the gameUpdate does no more than 33.3ms.
    2. The changes I've made in the course of the gameUpdate causes a trigger pulse.
    3. This impulse is an event on the JavaFX application thread. Such an impulse ends a synchronization between the JavaFX application thread and a thread of rendering of the Prism.
    4. The gameUpdate runs on the same thread of request, so the pulse will run after the gameUpdate.
      By that I mean that the gameUpdate will never be interrupted by a pulse, which could cause the world to be returned in an intermediate state.
    5. Event handlers also run on the same thread, so I need not worry you synchronize them.
    6. Changes to the live nodes by event handlers will cause an additional impetus to be triggered.

    My questions are:

    1. I understand that correctly?
    2. When working with animations (for example. RotateTransition), this animation triggers its own pulses, actually being run to a framerate higher than the loop game?

    Thank you!

    > I tried AnimationTimer also, but that does not seem suited to the steps of fixed time...: 'the AnimationTimer class to create a timer, which is called in each frame, while it is active. This seems to indicate that the timer is called on each pulse...

    Yes, this is how the timer works, it is called on each pulse.  Generally, the pulse occurs regularly, 60 times per second.  However, if your code (or internal JavaFX code), a lot of work to do on a given pulse, for example you added 100 000 rectangles at the scene, then the impulse will have more than 1/60th of a second.  The AnimationTimer provides a hook you can hang off of to execute logic when occurs a pulse, but how many times it is called depends on the current frames per second (FPS), which the application is running under (which can vary from an intensive application graphic or logic).

    --------

    > I understand that well?

    I think that understanding is generally correct, except for the statement about additional impulses.

    > The changes that I made during the gameUpdate causes a trigger pulse... Changes to the live nodes by event handlers will cause an additional impetus to be triggered.

    This is not really correct.   Pulse will always occur 60 times per second (or as soon as possible if the FPS is less than 60 FPS).  Nothing in the application causes an additional impetus.  However, if the application scene is static and don't change not, then pulse runs very quickly because he has little work to do.  JavaFX has mechanism of sale under construction node.  Only Sales (or modified) nodes are displayed on each pulse.  Between pulses, JavaFX will merge all the changes at the scene to determine all the nodes for a given impulse Sales and just make these Sales nodes.

    For example, suppose that your chronology of animation for the game loop is set to trigger 30 times per second, then you could make a scene update on each pulse even.  If a scene update event handler is triggered on a strange impulse, an additional rendering will be on the pulse of odd to manage the sites updated.  If the same event handler is triggered on a same pulse, no additional rendering is required if the game loop is also updating the same nodes (because the nodes are already filthy and dirty nodes are only displayed once per pulse).

    --------

    If you want a very reliable timer which is called like clockwork and is not the potential system hazards pulse JavaFX, then you can use a standard Java Timer, but in doing so, you leave the nature single-threaded protected JavaFX environment when you run the code in the timer, so the Timer code can not update to the live scene graph nodes.  If the timer changes the State of the game which is shared by the event handlers and other reminders that run on the JavaFX UI thread, you will require thread and data synchronization mechanisms, which could get complicated quickly.

    --------

    I think that on the whole, the recommendation would be to run your loop to 60 frames per second instead of 30 frames per second (how you can as well use an AnimationTimer), if you want the best perceived sharpness (in the case otherwise, you find yourself with questions stuttering as such as Nvidia g-sync technology is built to correct, but g-sync as the technology is not widespread).

    You can look at the code sample case brick (from Java Oracle 8 samples), because there were some changes to increase the fine (I think the code passed explicitly to a schedule that you set in your question to use the AnimationTimer, but check).

    The eppleton game engine also uses the approach of AnimationTimer because it is the game loop.

    -------

    > When working with animations (for example. RotateTransition), this animation triggers its own pulses, actually being run to a framerate higher than the loop game?

    Transition animations will be returned to each impulse, they trigger not their own pulse.  The animation can also trigger code to use (on the animation of JavaFX thread) when the time for a keyframe.

    -------

    I think that the way of thinking of time and transformation in JavaFX is that it is not continuous, but rather composed of discrete locations in which work can be done, if the slots correspond to each pulse and get up to 60 times per second.

  • game loop

    Can I move an image with a mouse and use a class to load the image.
    This works.

    T1) how can I put this code in a game loop in the file .fla that I need to move objects automatically? Can I use a timer or y at - it something better?

    Q2) how to report an event when the image of the ClassImg2 class has been loaded? I need to know this in the .fla file.

    below .fla file
    ////

    var li: ClassImg2 = new ClassImg2("ladybug.png",120,120);
    addChild (li);


    stage.addEventListener (KeyboardEvent.KEY_DOWN, doSomething);


    function doSomething(e:KeyboardEvent):void
    {

    arrow to the right of to //39 (e.keyCode == 37)
    {

    trace ("down left")
    Li.MoveLeft ();

    }

    arrow to the right of to //39 (e.keyCode == 39)
    {

    trace ("down right")
    Li.MoveRight ();

    }

    }

    "q1) how can I put this code in a game loop in the file .fla that I need to move objects automatically? Can I use a timer or y at - it something better? »

    It depends on the definition of "change". If you need a smooth animation - you will need an engine like TweenLite/TweenMax interpolation

    "q2) how to report an event when the image of the ClassImg2 class has been loaded. I need to know this in the .fla file. »

    Send the event to the class and listen to it on the timeline.

    Syntax for sending of the event:

    dispatchEvent (new Event ("eventTypeGoesHere"));

    Here's the documentation;

    http://www.Adobe.com/LiveDocs/Flash/9.0/ActionScriptLangRefV3/Flash/events/EventDispatcher .html#dispatchEvent%28%29

  • Tile game loop problem

    Hi all

    I make a game where you place the tiles on a grid. When you place a tile, I need to check the existence of another tile to the left, the right, or above and below, otherwise the tile should not be placed... Here is a function, I thought that would work, which accepts a variable (the position of the tile just as he is about to be placed): -.

    private void checkSurroundingTiles(gridPosition:uint) {}

    var gridPosition = T1 - 12;
    var t2 = gridPosition - 1;
    var T3 = gridPosition + 1;
    var T4 = gridPosition + 12;

    for (i = 0; i < gridRefArray.length; i ++) {}
    var checkTile = gridRefArray [i];

    if(checkTile == T1) {}
    Returns true;

    trace ("tile present above");
    } else if(checkTile == t2) {}
    Returns true;
    trace ("tile this left");
    } else if(checkTile == t3) {}
    Returns true;
    trace ("tile this right");
    } else if(checkTile == t4) {}
    Returns true;
    trace ("tile presents below")
    } else {}
    Returns false;
    }
    }
    }

    This works very well and gives a result... not reliable at 100% yet, but it's a work in progress... the problem I have is that I use a loop to get the position of the mosaic in the grid, and call the function during the loop made my computer hang because I'm checking the surrounding tiles on 132 grid references! Here is my code in a loop, can someone help me either remove the function of the loop or more efficient to find the answer: -.

    private void tileMouseUp(event:MouseEvent):void {}

    event.currentTarget.stopDrag ();

    for (i = 1; i < gridNum; i ++) {}

    If (Event.currentTarget.hitTestObject (gridArray [i]) & & .occupied gridArray [i] == true) {}
    event.currentTarget.x = event.currentTarget.origin.x;
    event.currentTarget.y = event.currentTarget.origin.y;
    } else if (event.currentTarget.hitTestObject (gridArray [i]) & & .occupied gridArray [i]! = true) {}

    checkSurroundingTiles (gridArray [i] .gridRef); That is the problem I think

    event.currentTarget.x = gridArray [i] .x + gamePage.grid.x;
    event.currentTarget.y = there gridArray [i] + gamePage.grid.y;

    gridArray [i] .occupied = true;
    gridRefArray.push (gridArray [i] .gridRef);

    }

    }

    Thanks in advance

    Yep

  • Make the loop freezes

    Hello.  I spent the last day or two, trying to figure out the best way to run my game loop.  Here's what I have to present based on examples I found. Thing is that the Simulator hangs during something like half a second when he makes a sound.  Does not matter if I use an alert or j2me stuff.  Note that this works on the storm.

    So I wonder if this method is wrong period.  I suppose I could mute for much of the development and use only on the storm but I'm worried that I'm going down the wrong path period.   I'm also surprised that javaloader is still requiring a reboot of the storm when I download, final COD looks like only 45 k.

    import java.util.*;
    
    import javax.microedition.media.*;
    import javax.microedition.media.control.*;
    
    import net.rim.device.api.system.*;
    import net.rim.device.api.ui.*;
    import net.rim.device.api.ui.component.*;
    import net.rim.device.api.ui.container.*;
    
    public class Tester extends UiApplication
    {
        public static void main( String[] args )
        {
            Tester app = new Tester();
    
            app.enterEventDispatcher();
        }
    
        public Tester()
        {
            pushScreen( new TesterScreen() );
        }
    }
    
    class TesterScreen extends FullScreen
    {
        static public final int     TickPerSec  = 30;
        static public final int     TickLength  = 1000 / TickPerSec;
        static public final int     ScrollSpeed = 10;
    
        private int             m_Tick = 0;
        private Timer           m_Timer;
        private TimerTask       m_TickTask;
    
        private long            m_TimeFPS;
        private long            m_TimeNow;
        private int             m_ElapsedFPS;
        private int             m_TickFPS;
        private String          m_TextFPS;
    
        private Bitmap          m_Background;
        private int             m_BackPos;
    
        private int             m_ToneMode = 0;
    
        private Player          m_Player;
        private ToneControl     m_ToneControl;
    
        static final short[]    m_Tones     = { 1400, 15, 1350, 15, 1320, 20, 1300, 20, 1250, 25, 1200, 35 };
        static final byte[]     m_Sequence  = { ToneControl.VERSION, 1,
                                                67, 16,
                                                69, 16,
                                                67,  8,
                                                65,  8,
                                                64, 48,
                                                62,  8,
                                                60,  8,
                                                59, 16,
                                                57, 16,
                                                59, 32,
                                                59, 32 };
    
        public TesterScreen()
        {
            m_Background = Bitmap.getBitmapResource( "img/splash.jpg" );
            m_BackPos    = 0;
    
            add( new BitmapField( m_Background ) );
    
            try
            {
                m_Player = javax.microedition.media.Manager.createPlayer( javax.microedition.media.Manager.TONE_DEVICE_LOCATOR );
                m_Player.realize();
                //m_Player.prefetch();
            }
            catch( Exception e )
            {
            }
    
            m_ToneControl = (ToneControl)m_Player.getControl( "ToneControl" );
            m_ToneControl.setSequence( m_Sequence );
    
            m_TimeFPS = new Date().getTime();
            m_TickFPS = m_Tick;
    
            m_Timer      = new Timer();
            m_TickTask = new TimerTask()
            {
                public void run()
                {
                    tick();
                }
            };
    
            m_Timer.schedule( m_TickTask, TickLength, TickLength );
        }
    
        public void destroy()
        {
            m_Background    = null;
            m_TickTask      = null;
            m_ToneControl   = null;
    
            if ( m_Timer != null )
            {
                m_Timer.cancel();
                m_Timer = null;
            }
    
            if ( m_Player != null )
            {
                m_Player.close();
                m_Player = null;
            }
        }
    
        public void tick()
        {
            if ( (m_Tick++ % (TickPerSec * 3)) == 0 )
            {
                try
                {
                    switch( m_ToneMode )
                    {
                        case 0:
                            break;
    
                        case 1:
                            if ( m_Player.getState() != Player.STARTED )
                                m_Player.start();
                            break;
    
                        case 2:
                            Alert.startAudio( m_Tones, 100 );
                            break;
                    }
                }
                catch( Exception e )
                {
                }
            }   
    
            m_BackPos += ScrollSpeed;
            if ( m_BackPos > m_Background.getHeight() )
               m_BackPos -= m_Background.getHeight();
    
            invalidate();
        }        
    
        public boolean keyChar( char key, int status, int time )
        {
            switch( key )
            {
                case Characters.ESCAPE:
                    close();
                    return true;
            }
    
            return false;
        }
    
        protected boolean touchEvent( TouchEvent message )
        {
            switch( message.getEvent() )
            {
                case TouchEvent.DOWN:
                    if ( ++m_ToneMode == 3 )
                        m_ToneMode = 0;
                    break;
            }
    
            return true;
        }    
    
        protected void paint( Graphics gd )
        {
            m_TimeNow    = new Date().getTime();
            m_ElapsedFPS = (int)(m_TimeNow - m_TimeFPS);
    
            gd.drawBitmap( 0, m_BackPos, Display.getWidth(), Display.getHeight(), m_Background, 0, 0 );
    
            if ( m_ElapsedFPS > 100 )
            {
                m_TextFPS = "FPS: " + (((m_Tick - m_TickFPS) * 1000) / m_ElapsedFPS);
                m_TickFPS = m_Tick;
                m_TimeFPS = m_TimeNow;
    
                //System.out.println( m_TextFPS );
            }
    
            gd.setColor( 0x00FF0000 );
            gd.drawText( m_TextFPS, 0, 0 );
        }
    
        public void onUiEngineAttached( boolean attached )
        {
            if ( attached == false )
                destroy();
        }
    }
    

    Leigh

    One thing having a TimerTask run so often (like you have with 33 milliseconds) and using Timer.schedule () is that late in running PPP executions all subsequent executions. Which means that if something (like audio) failed the system and delay your TimerTask, the animation (or you) will be very smooth, then he will have to "catch up". You can try to move to Timer.scheduleAtFixedRate () and add this at the beginning of your TimerTask.run)

    long currentTimeMillis = System.currentTimeMillis();long scheduledExecutionTime = scheduledExecutionTime();if ( currentTimeMillis - scheduledExecutionTime >= period ) {
    
        return;}
    

    Where in your case would be TickLength. Basically, it is saying that if execution is late enough where a subsequent run might have taken care of him already, then go this iteration because it will get handled by another.

  • need help on timer in math quiz game

    Hello, I have problem on my code on the timer.

    The code below is math quiz game, which player have only 1 min to answer all question of random math 30, if 1 min comes out or 30 were the answer, the game will end.


    First of all how can I set the current timer number if ill will less 10 sec of time

    Second mine
    If (Question 30 > | myTimer.currentCount > 60)
    {
    gotoAndStop (5);
    }
    does not work

    [AS]
    package
    {
    Add in your import here instructions
    import flash.display. *;
    import flash.events. *;
    import flash.utils.Timer;
    import flash.events.TimerEvent;

    //...


    SerializableAttribute public class MathsQuiz extends MovieClip
    {
    Add to your variables of class here
    private var score: Number;
    private var operand1:Number;
    private var operand2:Number;
    private var startNewGame:Boolean;
    private var Oper: int;
    private var Question: int = 1;
    public var delay: uint = 1000;
    public var: repeat: uint = 60;
    var myTimer:Timer = new Timer (delay, repeat);

    //...

    public void MathsQuiz()
    {

    }

    private void checkAnswer(evt:KeyboardEvent)
    {
    var userInput:int;
    var correctAns:int;

    switch (Oper)
    {
    case 0:
    If (evt.keyCode is 13)
    {
    userInput = Number (txtResult.text);
    correctAns = operand1 + operand2;

    If ((userInput is correctAns))
    {
    score += 10;
    Question += 1;
    startNewGame = true;
    }
    on the other
    {
    score = 5;
    myTimer.currentCount += 10;

    }
    txtResult.text = "";
    }
    break;
    case 1:
    If (evt.keyCode is 13)
    {
    userInput = Number (txtResult.text);
    correctAns = operand1 - operand2;

    If ((userInput is correctAns))
    {
    score += 10;
    Question += 1;
    startNewGame = true;
    }
    on the other
    {
    score = 5;
    myTimer.currentCount += 10;
    }
    txtResult.text = "";
    }
    break;
    case 2:
    If (evt.keyCode is 13)
    {
    userInput = Number (txtResult.text);
    correctAns = operand1 * operand2;

    If ((userInput is correctAns))
    {
    score += 10;
    Question += 1;
    startNewGame = true;
    }
    on the other
    {
    score = 5;
    myTimer.currentCount += 10;
    }
    txtResult.text = "";
    }
    break;
    case 3:
    If (evt.keyCode is 13)
    {
    userInput = Number (txtResult.text);
    correctAns = operand1 / operand2;

    If ((userInput is correctAns))
    {
    score += 10;
    Question += 1;
    startNewGame = true;
    }
    on the other
    {
    score = 5;
    myTimer.currentCount += 10;
    }
    txtResult.text = "";
    }
    break;
    }
    }

    public void startGame()
    {
    score = 0;
    Operand1 = 0;
    Operand2 = 0;
    Oper = 0;
    myTimer.addEventListener (TimerEvent.TIMER, update);
    myTimer.start ();
    startNewGame = true;
    Get the game loop to run

    addEventListener (Event.ENTER_FRAME, update);
    stage.addEventListener (KeyboardEvent.KEY_DOWN, checkAnswer);
    }

    public void update(evt:Event)
    {
    This is the game loop

    Manage the user input
    advanced feature addon:
    How to manage the entry of undetermined

    Manage the game logic
    Math.Random () =
    real number is between 0.0 1
    or MATH.floor (Math.random () * 13)
    If (Question 30 > | myTimer.currentCount > 60)
    {
    gotoAndStop (5);
    }
    ElseIf (startNewGame)
    {

    Operand1 = int (Math.random () * 13);
    Operand2 = int (Math.random () * 13);
    Oper = Math.floor (Math.random () * 4);
    startNewGame = false;

    }

    switch (Oper)
    {
    case 0:
    txtOper.text = ' + ';.
    break;
    case 1:
    txtOper.text = ' - ';.
    break;
    case 2:
    txtOper.text = ' * ';
    break;
    case 3:
    txtOper.text = ' / ';.
    break;
    }

    Manage the display
    txtOperand1.text = String (operand1);
    txtOperand2.text = String (operand2);

    txtScore.text = String (score);

    }
    } //end class
    } //end package
    [/ ACE]

    Use a separate variable to take into account rather than using the currentCount the timer.  Whenever the timer cycles add 1.  Whenever a wrong answer is given add 10.

    For the problem with your conditional that does not work, use the trace() function to see what the value of the Question and County are to see if they reach the values as you would expect they should.

  • AutoPlay

    When I insert a USB key or other removable media in my computer Windows Vista, I get a message from Microsoft Windows that gives me the choice to analyze media and solve any possible problem or I can continue without analyzing. After selection to continue without scan I get a message to AutoPlay with among the choices presented includes open folder to view files. When I select open folder to view files now, I opened with success the device as Microsoft intended. If my memory serves when AutoPlay indulged in versions of Windows prior to Vista there is a default read value automatic option which must be selected to access the removable media Auto play message, but it can be configured to automatically open the media when no current action or future required on the part of the user.

    Why Microsoft didn't put the requirements for response message in the automatic game loop to open the removable media in Windows? Under Xp, I could configure removable media to automatically open or stay closed without future liability or current response on my part is far from set Vista to automatically open a USB or for it remains closed without any action required from me other than the insertion of media in my computer?

    Sincerely,

    Mark

    Hello

    See if this helps you:

    Change AutoPlay settings.

    http://Windows.Microsoft.com/en-AU/Windows/Change-AutoPlay-settings#1TC=Windows-Vista

    "How to change the AutoPlay settings in Vista"

    http://www.Vistax64.com/tutorials/78021-AutoPlay-settings.html

    See you soon.

  • BB10 simulator: questions about the clock function

    I don't know, but I have the notion that under the Simulator for BB10 the clock() function returns a value of timer resolution of the host and not the right pair

    And since

    #define CLOCKS_PER_SEC 1000000

    during the conversion of the clock in seconds it will be least bad results under windows. Because Windows there

    #define CLOCKS_PER_SEC 1000

    I want to keep constant 60 FPS and I have a code like:

    const int FRAMES_PER_SECOND = 60;
    const int SKIP_TICKS = 1000 / FRAMES_PER_SECOND;

    int GetTickCount (void)
    {
    Return MathUtils::dti ((double) clock () / CLOCKS_PER_SEC);
    }

    and the game loop is:

    int t_prev = GetTickCount();

    mbGameRunning = true;
    While (mbGameRunning)
    {
    int t = GetTickCount();

    If ((t-t_prev) > SKIP_TICKS)
    Tick();

    Draw();

    EventLoop();

    t_prev = t;
    }

    Am I missing something?

    The clock() function only increments while your program is managed by the operating system. When the operating system switches to another task, "clock" your program stops running.

    You must use:

    clock_gettime(), which is the system clock that is still running.

  • Simple Threading Dillemma

    I have a thread main game loop, I want to run constantly in the background:

    import net.rim.device.api.ui.UiApplication;
    
    public class NewGame extends UiApplication {
    
        /* gameState amd newGameState:
         *      1 - Main Menu
         *      2 - Options
         *      3 - Help
         *      4 - About
         *      5 - Exit
         *      10 - Play Game
         */
        public int gameState = 0, newGameState = 1;
            private boolean stillAlive = true;
        public MainGameLoop mainGameLoop;
    
        MainMenu mainMenu = new MainMenu(this);
    
        public static void main(String[] args){
            NewGame newGame = new NewGame();
                    newGame.enterEventDispatcher();
        }
    
        public NewGame(){
                    mainGameLoop = new MainGameLoop();
        }
    
            private class MainGameLoop extends Thread
            {
                MainGameLoop()
                {
                    start();
                }
    
                public void run()
                {
                    while (stillAlive)
                    {
                        if (newGameState != gameState)
                        {
                            switch (newGameState)
                            {
                            case 1:
                                pushScreen(mainMenu);
                                gameState = newGameState;
                                Thread.yield();
                                break;
                            }
                        }
                    }
                    //Exit Game
                    System.exit(0);
                }
            }
    }
    

    When he pushes the main menu, I get an error as soon as starts to thread the main menu animation.  If I start the main menu thread without running the thread of the main loop of the game, it works perfectly.  Then, of course, I am unable to run these 2 threads at the same time.  I tried to give the first thread as soon as the main menu thread starts, but it does not help.

    I have also tried to main menu of sleep for 500ms ever iteration, even thought it is supposed to be suspended, but that didn't work either.

    Here is the thread from the main menu.  I removed all my personal code not covered do not threads:

    import net.rim.device.api.system.Bitmap;
    import net.rim.device.api.ui.Graphics;
    import net.rim.device.api.ui.container.FullScreen;
    
    public class MainMenu extends FullScreen
    {
        NewGame newGame;
        public MainMenuLoop mainMenuLoop;
        public boolean stillAlive = true;
        //Menu Item Chosen (0-Play Game, 1-Options, 2-Help, 3-About, 4-Exit)
        private byte menuItem = 0;
    
        MainMenu(NewGame m)
        {
            super(FullScreen.DEFAULT_MENU | FullScreen.DEFAULT_CLOSE);
            newGame = m;
    
            //Load images
    
            mainMenuLoop = new MainMenuLoop();
        }
    
        private class MainMenuLoop extends Thread
        {
            MainMenuLoop()
            {
                start();
            }
    
            public void run()
            {
                while (stillAlive)
                {
                //Menu animations code here
                    invalidate();
                }
            }
    
        }
    
        protected void paint(Graphics g)
        {
        //Drawing routine here
        }
    
        protected boolean navigationMovement(int dx, int dy, int status, int time) {
            //Check for Input from Trackball
            //Movement code here
            return true;
        }
    
        protected boolean navigationClick(int status, int time) {
            //Check for Clicks from Trackball
            return true;
        }
    
    }
    

    So, once more, if I call the main menu directly without using the main loop of the game, I have all the problems.  If I start the main loop of the game and call the main menu of him, I get an error when the thread starts.  Here is the error:

    JVM error 104

    Eception:

    IllegalStateException

    Thank you in advance!

    Keith

    As said previously, you don't need to run a thread explicitly to the "main menu" thread because stuff specific to the Blackberry user interface is already running within a thread, known as the "event thread". There are restrictions on other non-event threads trying to do some UI on the event from another thread thread (unless you synchronize on the lock event variable). When you gave birth to your thread and try to do things on the thread of the event, you will receive this exception.

  • How to make an object follow the mouseX when clicked on

    How to make an object follow the mouseX if clicked? Help, please.

    You should think it through - your code does not match your very simple explanation of what you say, it should do so, and it should... click an element and follow the mouse.

    A game loop (ENTER_FRAME) could work, but in this case it wastes unnecessary treatment if the mouse does not move.  And in your code example, it does not expect the clicks.

    Use a MOUSE_MOVE instead of an ENTER_FRAME event listener.  Inside of the event by clicking on the handler function is where you must be defined the MOUSE_MOVE listener.  The MOUSE_MOVE listener Manager is where you assign rock1Cnt.x = mouseX.

    public void Main (): void {}

    rock1Cnt.addEventListener (MouseEvent.CLICK, mouseClickHandler);

    }

    private void mouseClickHandler(e:MouseEvent):void {}

    stage.addEventListener (Event.MOUSE_MOVE, followMouse);

    }

    private void followMouse(e:MouseEvent):void {}

    rock1Cnt.x = mouseX

    }

  • Stupid questions on the conservation of important calls on the FX application thread

    I'm working on a project that I have developed for over 6 months. I use JavaFX as the graphic side, but I take admission to a program called Max/MSP of music therapy, and I get a camera user input. These two things should run on threads separated since my FX application thread. So far, things have been involved in sweetness. I can handle things on the screen of my user input, and I have two communication work between my application JavaFX and Max. Now, however, I need to start drawing things actually executing. So far, virtually all manipulations aside just summer FX do translations. I now need to create, add and delete nodes children. So, I am of course an error saying not "on the FX application thread. I understand why it is not on this thread, and why it is a problem. So I made a few changes, so that calls that change the nodes on the stage, will be noted only the data and then make the changes later on the FX application thread. And then I encounter problems, questioning my own stupidity...

    I don't know how to get these calls on the FX application thread. I mean, it must be really easy. I'm obviously missing something. Or maybe I'm really tired and reflected on this during too long, or maybe the fact that it's been 6 months I wrote this part of the code. But I see my Mainstage class, which extends the Application. It has a function of departure, that brings up all my on screen-dads (nodes and other scopes), called stage.show ()... and then seems to end. When I did things as calling translate functions on my knots in my thread of user input, or my thread communication Max, things seemed to have worked. But now I think I might have been handling this evil from the ground up. It seems probable that I should have a 'main game loop' (it's not really a game, but still, same principle) where I can say the scene to update all the different nodes with the changes that have occurred since the last frame, and try out everything be updated in time for graphics render at a reliable pace. And yet, I simply don't see how to do this. I'm sure this should be obvious, but I am flat by cutting. And the lack of time begins to descend... Please, if you can point some average standard to avoid this common newb mistake if everything goes well, I would be very happy!
    -Jean

    I think that last one. Each change of a node that is currently part of the scene displayed should be accessible from the thread of FX.

    If the node is not attached to a scene, or the scene itself is not currently displayed, you can make changes on any thread.

  • Why Flash will not read my ACE?

    Well I tried for days now to put a preloader in my code.  At the present time, that's what I'm looking for:

    This is the model preloader adobe gives you.  I have it in a frame on three layers.

    Stop();

    to import flash.events.ProgressEvent;

    import flash.events.Event;

    this.loaderInfo.addEventListener (ProgressEvent.PROGRESS, onLoading);

    this.loaderInfo.addEventListener (Event.COMPLETE, onComplete);

    function onLoading(evt:ProgressEvent):void {}

    var loaded: number = evt.bytesLoaded / evt.bytesTotal;

    percent_txt. Text = (loaded * 100) .toFixed (0) + "%";

    };

    function onComplete(event:Event):void {}

    this.loaderInfo.removeEventListener (ProgressEvent.PROGRESS, onLoading);

    this.loaderInfo.removeEventListener (Event.COMPLETE, onComplete);

    gotoAndStop (2);

    };

    This is my main class:

    Constructor method in which I can launch the menu

    public void Main()

    {

    menuLoop();

    trace ("why Hello!");

    }

    / * Here I add buttons.  The Play button will shoot

    the script of the loop menu and in the game loop * /

    public void menuLoop()

    {

    trace ("and how are you today?")

    menu.x = 200;

    menu.y = 240;

    stage.addChild (menu);

    playBttn.x = 175;

    playBttn.y = 300;

    stage.addChild (playBttn);

    playBttn.addEventListener (MouseEvent.CLICK, initGame)

    }

    Unfortunately, none of my kids actually added to the same screen if the result shows the friendly conversation, I traced.

    I have my ' export on frame: "2. I"Default connection"set to"merged into code."

    I added a second AS a frame in the timeline and added "stop()"; for stocks.  Everything was doing just that leaves me with a blank screen.

    I'm so desperate to make it work!  All advice is appreciated

    Thus, when you define playBtn = new play_button;

    It should run before the constructor. As do all your other statements where you define new someLibraryObject(). Therefore, at the time where the code even gets to your preloader, you have one of two situations (I don't know that, because I code on the timeline, in large part to cushion the compilation of the symbols in the swf file, reducing the need to still have a preloader library):

    1. Your main class cannot create the assets at the time wherever you tell him, because they are not compiled in yet. or
    2. They get compiled in because you are referencing them in image1, but because you have forced so many things to be loaded prior to frame 1, at the time wherever you see even the screen, the film is already loaded.

    DFO is that it probably is #1 based on the symptoms you report.

    So, let's try this:

    1. Delete 'Hand' outside the scope of the Document class.
    2. Create a new MC in your library and hand as its Base class.
    3. Place an instance of it as part 2.
    4. You can continue with the too complicated logic, you already have, or you could go with the simple/elegant solution of allowing the head to read just stop at the image of the compiler and play in frame 2, where you can put a stop() frame script.
    5. Return to the call of your mainLoop() directly from the constructor of the hand.

    Notes:

    1. The dominant convention have is to use the case with the first letter capitalized. This applies equally to the symbols of the library.
    2. To generate a report of size, click the 'generate size report"box in publication settings. It will be a text next to the SWF file.
  • How to suspend a timer?

    IM finishing of one of my many projects, I HATE UI! and I read about 7 things to avoid on how to make a shitty game and one of them had a pause button, I managed to add all the other things, but im absolutely stumped on a pause button. I read a tutorial, which has not really helped. He was talking about a game loop main and all that crap coming puzzle me. I tried it, and I don't have any errors, just a LOT of laf, because what I did was put all my code Builder in the "update" function, then it is running my enemies spawn each image ect. but the realized all i do I have to break my timer, because it's the only thing that really needs to be done? I read somewhere on the timers with getTimer suspension, but that confused me that wasn't where really explain the concept to just give the answer really. Can someone help me please?

    Here is my timer:

    public function setCrates()
                        {
                                  DropCrate = new Timer(10000+Math.random()*10000,1);
                                  DropCrate.addEventListener(TimerEvent.TIMER_COMPLETE, newCrate);
                                  DropCrate.start();
                        }
    
    
                        public function newCrate(Event:TimerEvent)
                        {
                                  var StartPosition:Number = Math.random() * 90 + 10;
    
    
                                  // create plane
                                  var c:Crate = new Crate(StartPosition);
                                  addChild(c);
                                  Crates.push(c);
    
    
                                  setCrates();// set time for next crate;
                        }
    
    

    This is the game loop thing I was talking about:

    package 
    {
     import flash.display.MovieClip;
     import flash.events.Event;
    
     public class Main extends MovieClip
     {
     private var isPaused:Boolean; // This is the variable that holds our paused/unpaused state
    
     public function Main()
     {
     // Unpause the game:
     isPaused = false; 
     // Add an event listener to keep an eye (ear?) on the built-in ENTER_FRAME event.
     // Every time Flash processes a frame tick, doMasterGameLoop will execute:
     addEventListener(Event.ENTER_FRAME, doMasterGameLoop);
     }
    
     private function doMasterGameLoop(e:Event = null):void
     {
     // This is the main game loop that does all the work.  It's the
     // "gateway" to everything our game does.  If the game is paused,
     // nothing in the game loop happens.
     if (!isPaused)
     {
     update();
     draw();
     } 
     }
    
     private function update():void
     {
     // Tweak all your numbers and math stuff here
     }
    
     private function draw():void
     {
     // Update all your graphics here 
     }
     }
    }
    
    

    Here is what im using for my enemy:

                             public function setNextEnemy()
                        {
                                    nextEnemy = new Timer(1000+Math.random()*1000,1); // I replaced the PausableTimer with this one again
                                  nextEnemy.addEventListener(TimerEvent.TIMER_COMPLETE,newPlane);
                                  nextEnemy.start();
                        }
    
                        public function newEnemy(event:TimerEvent)
                        {
                                  // im spawing the enemies from a random side of the stage
                                  if (Math.random() > .5)
                                  {
                                            var side:String = "left";
                                  }
                                  else
                                  {
                                            side = "right";
                                  }
                                  var altitude:Number = Math.random() * 90 + 10;
                                  var speed:Number = Math.random() * 100 + 150;
    
                                  // create plane
                                  var e:Enemy = new Enemy(side,speed,altitude);
                                  addChild(e);
                                  Enemies.push(e);
                                  setNextEnemy();// set time for next plane;
                        }
    
  • Help with error 1180

    Hello

    Sorry I am new to the forum and all that. I'm trying to copy a youtube tut and we came to a mistake and can't seem to fix it. I followed everything exactly and you still get the error twice. The error I get is the following.

    I hope someone can help.

    Line 42 1180: Call to a possibly undifned method aMissleArray. (Line 42 highlighted in red)

    See code below:

    Kind regards

    Brendan

    firstGamemcMissle

    package

    {

    import flash.display.MovieClip;

    import flash.events.Event;

    import flash.events.KeyboardEvent;

    /**

    * ...

    * @author Brendan Maurer

    */

    public class firstGame extends MovieClip

    {

    public var mcPlayer:MovieClip;

    private var leftKeyIsDown:Boolean;

    private var rightKeyIsDown:Boolean;

    private var aMissleArray:Array;

    public void firstGame()

    {

    Initialize variables

    aMissleArray = new Array();

    trace ("firstGame game loaded")

    Configure listeners to enumerate, for when the key

    stage.addEventListener (KeyboardEvent.KEY_DOWN, keyDown);

    stage.addEventListener (KeyboardEvent.KEY_UP, keyUp);

    Configure a game loop event listener

    stage.addEventListener (Event.ENTER_FRAME, gameLoop);

    }

    private void gameLoop(e:Event):void

    {

    playerControl();

    clampPlayerToStage();

    checkMisslesOffScreen();

    }

    private function checkMisslesOffScreen (): void

    {

    Browse all of our missles in our table of missile

    for (var i: int = 0; i < aMissleArray.length; i ++)

    {

    Get current missiles in the loop

    var currentMissle:mcMissle = aMissleArray (i);

    Test if the current missile went from the upper part of the scene

    If (currentMissle.y < 0)

    {

    Remove the current missile of the table

    aMissleArray.splice (i, 1);

    Destroy missiles

    currentMissle.destroyMissle ();

    }

    }

    }

    private function clampPlayerToStage (): void

    {

    If our player's stage left

    If (mcPlayer.x < mcPlayer.width/2)

    {

    Put our reader t that he stage left

    mcPlayer.x = mcPlayer.width/2;

    }

    If our player is to the right of the stage

    If (mcPlayer.x > (stage.stageWidth - (mcPlayer.width / 2)))

    {

    Put our drive t he right of the scene

    mcPlayer.x = stage.stageWidth - (mcPlayer.width / 2);

    }

    }

    private void control drive (): void

    {

    If the key to our left is currently unavailable

    If (leftKeyIsDown is true)

    {

    Our player move left

    mcPlayer.x-= 5;

    }

    If the key to our right is currently unavailable

    If (rightKeyIsDown)

    {

    Playewr move right

    mcPlayer.x += 5;

    }

    }

    private void keyUp(e:KeyboardEvent):void

    {

    trace (e.keycode)

    If the left button is released

    If (e.keyCode is 37)

    {

    Left button is released

    leftKeyIsDown = false;

    }

    If our key law is released

    If (e.keyCode is 39)

    {

    Right key is released

    rightKeyIsDown = false;

    }

    If the space is freed

    If (e.keyCode is 32)

    {

    Fire a missile

    fireMissle();

    }

    }

    private function fireMissle (): void

    {

    Create a new object of missile

    var newMissle:mcMissle = new mcMissle();

    Add this missile to the scene

    stage.addChild (newMissle);

    Position our missile is on top of our player

    newMissle.x = mcPlayer.x;

    newMissle.y = mcPlayer.y;

    Add new missile missile table

    aMissleArray.push (newMissle);

    trace (aMissleArray.Length)

    }

    private void keyDown(e:KeyboardEvent):void

    {

    trace (e.keycode)

    If our left is pressed

    If (e.keyCode is 37)

    {

    Left key

    leftKeyIsDown = true;

    }

    If our right is pressed

    If (e.keyCode is 39)

    {

    Right key

    rightKeyIsDown = true;

    }

    }

    package

    {

    import flash.display.Sprite;

    import flash.events.Event;

    /**

    * ...

    * @author Brendan Maurer

    */

    public class mcMissle extends Sprite

    {

    public void mcMissle()

    {

    An event listener to see if our missiles is added to the configuration step

    addEventListener (Event.ADDED_TO_STAGE, onAdd);

    }

    private void onAdd(e:Event):void

    {

    removeEventListener (Event.ADDED_TO_STAGE, onAdd);

    Now that our object is on the scene to execute our code custom

    init();

    }

    private function init (): void

    {

    addEventListener (Event.ENTER_FRAME, missleLoop);

    }

    private void missleLoop(e:Event):void

    {

    This.y-= 10;

    }

    public function destroyMissle (): void

    {

    Remove the object from the stage

    parent.removeChild (this);

    Remove event listeners

    removeEventListener (Event.ENTER_FRAME, missleLoop);

    }

    }

    }

    At first glance, it appears that incorrectly, you are trying to access a member of an array, which was considered that it is a function...

    var currentMissle:mcMissle = aMissleArray (i);

    should be

    var currentMissle:mcMissle = aMissleArray [i];

    I'm not very good in class, but I wonder why you do not declare the variable at the beginning like others.  In addition, I don't see where you import the class cars, so I have to wonder if this could be a problem as well.

  • Problemo

    I'm having a weird problem and wonder if anyone can help me fix. I'm doing a game with a spaceship of player controlled by the keyboard input. But he doesn't move with the keyboard until I click on the mouse button. the problem may be with the game framework that I use for a download for the book, "the Essential Guide to Flash games", but maybe it's something I am doing wrong in the code. I have the variables _vx and _vy, initially set to zero while they are supposed to change when I press the arrow keys, so that the ship to move. Here's the class with the typing in it...

    package

    {

    / / Import the required classes of flash libraries

    import flash.display.Sprite;

    import flash.events. *;

    import flash.events.MouseEvent;

    import flash.events.KeyboardEvent;

    import 12345678910111213import;

    import flash.display.BitmapData;

    import flash.geom.Point;

    import flash.ui.Mouse;

    import flash.ui.Keyboard;

    import com.efg.framework.CustomEventSound;

    import com.efg.framework.Game;

    import com.efg.framework.CustomEventLevelScreenUpdate;

    import com.efg.framework.CustomEventScoreBoardUpdate;

    /public class Lunar_Mayhem extends game

    {

    gameWidth:int private var;

    gameHeight:int private var;

    Private const SPEED: Number =. 4;

    //New game

    private var score: int;

    private var level: int;

    private ships var int;

    private var calls: int;

    private var isGameOver:Boolean = false;

    //New level

    explodeArray:Array private var;

    shotArray:Array private var;

    shipArray:Array private var;

    crosshairs:Bitmap private var;

    public var _vx:Number = 0;

    public var _vy:Number = 0;

    tempShot:Shot private var;

    _player:Ship private var;

    //private var testLevel:TestLevel;

    private var tempShip: ship;

    //private var tempExplode:Explosion;

    public void Lunar_Mayhem() {}

    init() ;

    //testLevel = new TestLevel (_vx, _vy);

    / / this.addChild (testLevel);

    //tempShot = new ((testLevel._player.x +testLevel._player.width/2-5) Shot, (testLevel._player.y + testLevel._player.height/2),0,0);)

    }

    public void init () {}

    }

    override public function newGame (): void {}

    level = 0;

    score = 0;

    ships = 3;

    shots = 0;

    isGameOver = false;

    stage.addEventListener (KeyboardEvent.KEY_DOWN, onKeyDown);

    stage.addEventListener (KeyboardEvent.KEY_UP, onKeyUp);

    }

    onKeyDown(e:KeyboardEvent):void of the public service

    {

    switch (e.keyCode)

    {

    Case Keyboard.LEFT:

    _vx = SPEED *. 5;

    break;

    Case Keyboard.RIGHT:

      _vx += SPEED * .5;

    break;

    Case Keyboard.UP:

    _vy-= SPEED;

    break;

    Case Keyboard.DOWN:

    break;

    }

    }

    onKeyUp(e:KeyboardEvent):void of the public service

    {

    if (e.keyCode == Keyboard.LEFT

    || e.keyCode is Keyboard.RIGHT)

    {

       //_vx = 0;

      }

    If (e.keyCode is Keyboard.UP

      || e.keyCode is Keyboard.DOWN)

    {

       //_vy = 0;

      }

    }

    override public function newLevel (): void {}

    _player = new Ship();

    this.addChild (_player);

    explodeArray = [];

    shotArray = [];

    shipArray = [];

    level ++;

    dispatchEvent (new CustomEventLevelScreenUpdate (CustomEventLevelScreenUpdate.UPDATE_TEXT, String (level)));

    dispatchEvent (new CustomEventScoreBoardUpdate (CustomEventScoreBoardUpdate.UPDATE_TEXT, Main.SCORE_BOARD_SHOT S, String (shots)));

    dispatchEvent (new CustomEventScoreBoardUpdate (CustomEventScoreBoardUpdate.UPDATE_TEXT, Main.SCORE_BOARD_SHIP S, String (ships)));

    }

    override public function runGame (): void { }

    update (_vx, _vy);

    render();

    checkCollisions();

    checkforEndLevel();

    checkforEndGame();

    trace (_vy);

    trace (_vx);

    }

    I have only included as code because I think that's the problem. Public override function runGame is the game loop. updated and make it call the class of ship that looks like this:
    package
    {
    / / Import the required classes of flash libraries
    import flash.display.Shape;
    import flash.display.Sprite;
    import flash.events. *;
    import 12345678910111213import;
    import flash.display.BitmapData;
    import flash.geom.Point;
    /**
    * ...
    */
    ship/public class extends Sprite
    {
    Private const SPEED: Number =. 4;
    gameWidth:int private var;
    gameHeight:int private var;
    public var imageBitmapData:BitmapData;
    public var image: Bitmap image;
    public var nextLocation:Point;
    public var playerHalfWidth:Number;
    public var playerHalfHeight:Number;
    //scroll with variables of player
    public var gravity: Number;
    private var _energy:Number = 100;
    private var hitVal:Number = 0;
    public Ship() void {}
    init();
    }
    public function init (): void { }
    //***** Flex *****
    //imageBitmapData = new ShipGif () .bitmapData;
    //**** Flash *****
    nextLocation = new Point (0,0).
    imageBitmapData = new ShipGif (63, 53);
    image = new Bitmap (imageBitmapData);
    addChild (image);
    gameWidth = 550;
    gameHeight = 400;
    gravity =. 55;
    playerHalfWidth = 63 / 2;
    playerHalfHeight = 53 / 2;
    }
    public void update(_vx:Number,_vy:Number):void {}
    nextLocation.x += _vx;
    nextLocation.y += _vy;
    nextLocation.y += gravity;
    }
    public void render (): void {}
    x = nextLocation.x;
    = nextLocation.y;
    }
    //Dispose is necessary to get rid of unwanted objects oo and prepare them for garbage collection
    public void willing (): void { }
    removeChild (image);
    imageBitmapData.dispose ();
    image = null;
    }
    }
    }
    If someone could take a look and see what the problem would be great. Thank you

    Use the trace() function to debug your code.  It is usually easier to work back and forth checking the lines of code that, do you think, should cause your ship move.  keep working backwards until you find the immediate cause of the problem.

Maybe you are looking for

  • 10 Firefox does not prompt for passwords recording

    Even if the Save password option is checked, and I'm not in private browsing mode prompt "pop-up" to save passwords doesn't seem anymore. Some sites do not allow this function, however, it does not appear on all sites (sites that work with a 10 Firef

  • Error code: 646 (cannot install KB2289116)

    THIS UPDATE WON'T INSTALL, I DO NOT HAVE OUTLOOK 2010 BUT I DON'T HAVE OFFICE 2010... I DOWNLOADED THE UPDATE SEPARATELY BUT STILL GET AN ERROR... THAT HE FAILED. 646 ERROR CODE

  • Cannot remove a program from the start menu icon

    Original title: icons in the Start Menu;. Cannot delete the program start menu icon to remove/uninstall, need help? S pie Menu icons; Ghost of icons I deleted a program and uninstalled completely, but the program icon always appears in the start menu

  • Mouse/Touchpad

    I can't get the touchpad on my laptop to work right. It works fine most of the time, but when I try to rub my finger on the side or on the bottom to simulate scroll it to the bottom of the wheel bearing on a conventional mouse, it does nothing. What

  • Loop on the life list

    How can I loop over alistview I have? and make a difference in this asyncrhonusly. like here, I want to access the imageview to set the image once that I get them from a certain url. ListView { layout: StackListLayout { orientation: LayoutOrientation