Home‎ > ‎

Making Objects Move By Themselves

A better way is to have the object move every time interval itself

You could create a self-running function which waits 2 seconds then sends itself a message. It then moves the object, waits again 2 seconds then sends itself a message. This goes on forever once you start it.

Add the following code to your Card Script, below all your other code.

        on moveObj
            put random(400) into x
            put random(600) into y
            set loc of graphic “diamond” to x,y

            send “moveObj” to me in 2 seconds
        end moveObj


To start it, either add a button which sends it the first message “moveObj” or add the message when you open the card

        on openCard
            moveObj
        end openCard



Stopping it !! (Very Important)

You want it to stop after the game is over or whenever you go to another level (card). If you don't stop it, it will run on forever, or worse - cause your game to stop with an error. 

( When you go to another card, it may not have a "moveObj" message handler. So the message "moveObj" will be sent to the new card in 2 seconds and it will not know what to do.)

So we need to tell it when to stop sending itself the message. We use a variable for this and set it to either true or false.


    Add on the card script at the top:

        global stillGoing

   Add on the card script in the openCard handler:

         on openCard
              put true into stillGoing
              moveObj
         end openCard
    
    Add on the card script in your moveObj handler:

        command moveObj
            if stillGoing then
                put random(400) into x
                put random(600) into y
                set loc of graphic “diamond” to x,y
                send “moveObj” to me in 2 seconds
            end if
        command moveObj

   Add on the card script whenever you stop the game or go to another card:

              put false into stillGoing
 

Comments