Hi Hops - Today I thought I’d show you a way to code When Pressed followed by When Released all within one event (When Rule)
- Drag an object when pressed, then do something specific when released
- Make a button change when pressed, then “click” (do what ever) when released
First, however, I’ll refer you back to the
Tutorial: Using Constants (and custom rule: Watch Pressed State). That topic shows a different way the same effect could be achieved. But when you specifically want a When Pressed that’s followed by a When Released, the method I’ll show below is a bit more elegant. If you haven’t read that topic or haven’t started using constants when you code, I highly recommend reading it and you’ll be coding like a pro in no time.
The order of objects is important so let’s have a look at the list of objects in my example:
The rules within the objects will execute sequentially in the order that the objects are in. Almost every project I make has Main as the first object. It’s just a blank text object. I use this to hold When Game Starts rules that I want to execute first (if you’re not sure why that matters, read the tutorial on constants linked above) or to hold rules I want to execute 1st during every frame.
So, we’re coding a chess game and want the pieces to drag when pressed, then snap to the center of the nearest square when released. How should we do that? Don’t worry. I won’t go into all that detail, but let’s see how to set it up so the code executes when we want it to.
The first thing we want to happen every frame, is to set a boolean (that’s a variable that equals either 1 or 0) to indicate if the device is being pressed during that frame. So we add this to the object Main:
Then we added a When (self) is Pressed to the desired object(s). Inside there, we’ll use recursion to get the 1st section of code to loop (note the ‘Drag until released’ ability directs the code back to itself) while the device /object is pressed. Then when the Main object sets the variable Pressed to 0 (when the press is released), it continues on to where we’ll put the code that should run when the object is released.
And that’s it. A simple, elegant solution for When Pressed followed by When Released.