How do I create a speed boost in CS6 AS2? - performance

I'm using Flash CS6 with AS2.
I'm in a Game Design class here in High School and we have learned some basic coding. I am currently trying to add a "speed boost" feature when you press the shift button. You're supposed to be able to press it and that would give you a 5 second speed boost. After those 5 seconds, you'd revert back to normal speed. These are the variables I have made:
speed = 6;
boost = 16;
boost_timer = 0;
I've set my speed to 6, and I called 16 (the ASCII code for the Shift Key) "boost". I've also added in a timer for the boos to count to the 5 seconds when I call for it in the main code. Here that part of the code:
if(Key.isDown(boost))
{
speed = 0;
boost_timer++;
speed = 12
}
-
if(boost_timer >= 5)
{
boost_timer = 0;
speed = 6;
}
Now, what I'm trying to do here is make it so that when I press "boost", it will set my "boost_timer" to 0 (which would only matter if and when it's not already at 0). Then, it will start increasing my "boost_timer" and set my "speed" to double the original speed.
In the second piece of code, I make it so that once it reaches 5, it should set the timer back to 0. However, because "boost_timer++" had already been set, even with it getting set back to 0, it would still be increasing. But, even when it gets to 5, it will simply restart the timer and continue resetting the speed to 6. The next time I press the "boost" button, it should set the "boost_timer" back to 0 and re-do the whole thing.
I am planning on adding some sort of power up function for later that will restrict the amount of times you can use the boost, but for now, I would first like to make sure that my game is actually capable of using the boost multiple times.
The actual problem I'm having with the coding I have so far is that whenever I now press the "boost" button, it does, in fact, increase the speed. However, it stays at the boosted speed and never goes back on its own. And for some reason, whenever I press the "boost" button again while already boosted, it reverts back to original speed. It's as if the "boost" button is working as an activate and deactivate button for the boost, but I have no idea why and what part of my code is causing this.
Thank you very much for any help you can give!

Found an answer for you from newgrounds:
If you just want to test if the key isnt pressed at the time, just use:
if(Key.isDown(Key.UP) == false)
or
if(!Key.isDown(Key.UP))
however, if you want to test for the exact point the key is lifted only, you have to use a latch sysetm:
if(Key.isDown(Key.UP)){
latch = true;
}
if(!Key.isDown(Key.UP) && latch){
latch = false;
// put your actions here
}
you can see that it will only be that !Key.isDown(Key.UP) && latch once after the key is pressed, so it will perform the actions,then
will wait until the key is pressed then released again to do the
actions again.
And you shall probably run some function at the point where key is lifted up, to reduce speed and store speed boost leftover values.
also this latch variable shall be set to false on every frame at the point where no more functions precedes, so after event program enters next frame with its value being false
Umh! There is event listener for this already made: adobeMX

Related

how to change stepper direction through limit switch

I am working on a project and am trying to write code for this project in circuitpython on a esp32 s2 board.
Currectly I don't have the hardware setup ready to function so I can't test codes I've written. So all I have to base my findings on are thought experiments and trying to understand what the code will do (which is a good training at it's own IMHO).
One of the difficulties, and the one for this question, is that I am dealing with getting the stepper motor to change direction when an (optical) limit switch is triggered (so far so good i think), but i will also need to keep it in this "reversed" direction once it no longer triggers that switch.
One way, to do so, seems to make it stop looking at the first limit switch as soon as it is triggered and start looking at the switch at the opposite end instead as well as change the direction. Unfortunately i understand this but have no clue how to set this up in code. When it reaches the trigger it this end it needs to do something else entirely so i am really only dealing with this one switch triggered change of direction during initialisation.
while True:
stepper_motor.onestep(direction=stepper.FORWARD, style=stepper.DOUBLE)
time.sleep(Interstep_delay)
while switch_top.value is False
stepper_motor.onestep(direction=stepper.BACKWARD, style=stepper.DOUBLE)
Step_count = Step_count + 1
time.sleep(Interstep_delay)
while switch_bottom.value is False
#stop stepper motor
Total_count = Step_count.
This is the code I have for now, but it just doesn't feel correct to me. Mainly because I (think I) make it look at the bottom switch but I don't make it stop looking at the top switch but I have no idea how to change this in a correct manner.
Any thought and suggestions are welcome.
Kind greats
PS: I added my code to clarify what I am doing and willing to do. Please help me with the thought experiment. This question is ofcourse not intended for me to end up with a working code still don't understand.
Since post i changed code to this
# initiasation
leds[0] = (255, 0, 0)
while True:
while switch_top.value:
stepper.onestep(direction=stepper.FORWARD, style=stepper.DOUBLE)
time.sleep(Interstep_delay)
if switch_bottom.value:
stepper.onestep(direction=stepper.BACKWARD, style=stepper.DOUBLE)
Step_count = Step_count + 1
time.sleep(Interstep_delay)
elif switch_bottom.value is False:
Step_count = Total_steps
leds[0] = (0, 255, 0)
if switch_start is False:
leds[0] = (0, 0, 255)
game_function()
but i am still in doubt if it would actually do what i intend it to do.

Qtimer: calling different slot every 2000 ms

I'm working on a project but I'm new of c++ and Qt and I'm having some big troubles.
I have my program on Qt with my GUI interface and I already have done all the Slots related to the buttons in the GUI. Now what I need is to call different slot in sequences every 2000ms, to explain better, the Slots are for example
void on_setPort_clicked();
void on_portSearch_clicked();
void on_openPort_clicked();
void on_ledON_clicked();
I need the program (when I push the relative button) to execute the first one, then after 2 second the second one, then after 2 second again the third one and so on...
How can I do this? For now I understood how to make a certain Slot to execute every 2 second but I need to have a different slots every 2 seconds. I dont know what to put in my .h file and in my .cpp
Thanks guys, hope to have been clear in my answer, sorry for my english but I'm italian.
PS I also need a slot like for examples on_STOP_clicked with a command that will stop sequences to continue like a timer stop when I push the relative button in the GUI
QT Slots are just normal functions so what you need to do is have the timer call one slot and then have that slot determine which function should be called next and then call it.
//State held somewhere else that makes sense in your progrma
//preferably not just a global
int nextSlot =0;
void timer_slot(){
switch(nextSlot){
case 0:
first_slot();
break;
case 1:
second_slot();
break;
etc....
}
nextSlot++ % (number_of_other_functions-1);//-1 as the array is 0 indexed
}
}

glutMainLoop() vs glutTimerFunc()?

I know that glutMainLoop() is used to call display over and over again, maintaining a constant frame rate. At the same time, if I also have glutTimerFunc(), which calls glutPostRedisplay() at the end, so it can maintain a different framerate.
When they are working together, what really happens ? Does the timer function add on to the framerate of main loop and make it faster ? Or does it change the default refresh rate of main loop ? How do they work in conjunction ?
I know that glutMainLoop() is used to call display over and over again, maintaining a constant frame rate.
Nope! That's not what glutMainLoop does. The purpose of glutMainLoop is to pull operating system events, check if timers elapsed, see if windows have to be redrawn and then call into the respective callback functions registered by the user. This happens in a loop and usually this loop is started from the main entry point of the program, hence the name "main - loop".
When they are working together, what really happens ? Does the timer function add on to the framerate of main loop and make it faster ? Or does it change the default refresh rate of main loop ? How do they work in conjunction?
As already told, dispatching timers is part of the responsibility of glutMainLoop, so you can't have GLUT timers without that. More importantly if there happened no events and no re-display was posted and if there's not idle function registerd, glutMainLoop will "block" the program until some interesting happens (i.e. no CPU cycles are being consumed).
Essentially it goes like
void glutMainLoop(void)
{
for(;;){
/* ... */
foreach(t in timers){
if( t.elapsed() ){
t.callback(…);
continue;
}
}
/* ... */
if( display.posted ){
display.callback();
display.posted = false;
continue;
}
idle.callback();
}
}
At the same time, if I also have glutTimerFunc(), which calls glutPostRedisplay() at the end, so it can maintain a different framerate.
The timers provided by GLUT make no guarantees about their precision and jitter. Hence they're not particularly well suited for framerate limiting.
Normally the framerate is limited by v-sync (or it should be), but blocking on v-sync means you can not use that time to do something usefull, because the process is blockd. A better approach is to register an idle function, in which you poll a high resolution timer (on POSIX compliant systems clock_gettime(CLOCK_MONOTONIC, …), on Windows QueryPerformanceCounter) and perform a glutPostRedisplay after one display refresh interval minus the time required for rendering the frame elapsed.
Of course it's hard to predict how long rendering is going to take exactly, so the usual approach is to collect sliding window average and deviation and adjust with that. Also you want to align that timer with v-sync.
This is of course a solved problem (at least in electrical engineering) which can be addressed by a Phase Locked Loop. Essentially you have a "phase comparator" (i.e. something that compares if your timer runs slower or faster than something you want synchronize to), a "charge pump" (a variable you add to or subtract from the delta from the phase comparator), a "loop filter" (sliding window average) and an "oscillator" (a timer) controlled by the loop filtered value in the charge pump.
So you poll the status of the v-sync (not possible with GLUT functions, and not even possible with core OpenGL or even some of the swap control extensions – you'll have to use OS specific functions for that) and compare if your timers lag beind or run fast compared to that. You add that delta to the "charge pump", filter it and feed the result back into the timer. The nice thing about this approach is, that this will automatically adjust to and filter the time spent for rendering frames as well.
From the glutMainLoop doc pages:
glutMainLoop enters the GLUT event processing loop. This routine should be called at most once in a GLUT program. Once called, this routine will never return. It will call as necessary any callbacks that have been registered. (grifos mine)
That means that the idea of glutMainLoop is just processing events, calling anything that is installed. Indeed, I do not believe that it keeps calling display over and over, but only when there is an event that request its redisplay.
This is where glutTimerFunc() comes into the play. It register a timer event callback to be called by glutMainLoop when this event is triggered. Note that this is one of several possible others event callbacks that can be registered. That explains why in doc they use the expression at least.
(...) glutTimerFunc registers the timer callback func to be triggered in at least msecs milliseconds. (...)

Why does EnvGen restart on every loop iteration and how to prevent this behavior?

How can I use EnvGen in a loop in such a way that it won't restart at every iteration of the loop?
What I need it for: piecewise synthesis. I want e.g. 50ms of a xfade between first and second Klang, then a 50ms xfade between second and third Klang, then a 50ms xfade between third and fourth Klang and so on, and I want this concatenation as a whole to be modulated by an envelope.
Unfortunately the EnvGen seems to restart from the beginning on every iteration of the loop that plays the consecutive Klang pairs. I want a poiiiiinnnnnnnnnng, but no matter what I try all I get is popopopopopopopopo.
2019 EDIT:
OK, since nobody would answer the "how to achieve the goal" question, I am now downgrading this question to a mere "why doesn't this particular approach work", changing the title too.
Before I paste some code, a bit of an explanation: this is a very simplified example. While my original desire was to modulate a complicated, piecewise-generated sound with an envelope, this simplified example only "scissors" 100ms segments out of the output of a SinOsc, just to artificially create the "piecewise generation" situation.
What happens in this program is that the EnvGen seems to restart at every loop iteration: the envelope restarts from t=0. I expect to get one 1s long exponentially fading sound, like plucking a string. What I get is a series of 100ms "pings" due to the envelope restarting at the beginning of each loop iteration.
How do I prevent this from happening?
Here's the code:
//Exponential decay over 1 second
var envelope = {EnvGen.kr(Env.new([1,0.001],[1],curve: 'exp'), timeScale: 1, doneAction: 2)};
var myTask = Task({
//A simple tone
var oscillator = {SinOsc.ar(880,0,1);};
var scissor;
//Prepare a scissor that will cut 100ms of the oscillator signal
scissor = {EnvGen.kr(Env.new([1,0],[1],'hold'),timeScale: 0.1)};
10.do({
var scissored,modulated;
//Cut the signal with the scisor
scissored = oscillator*scissor;
//Try modulating with the envelope. The goal is to get a single 1s exponentially decaying ping.
modulated = {scissored*envelope};
//NASTY SURPRISE: envelope seems to restart here every iteration!!!
//How do I prevent this and allow the envelope to live its whole
//one-second life while the loop and the Task dance around it in 100ms steps?
modulated.play;
0.1.wait;
});
});
myTask.play;
(This issue, with which I initially struggled for MONTHS without success, actually caused me to shelve my efforts at learning SuperCollider for TWO YEARS, and now I'm picking up where I left off.)
You way of working here is kind of unusual.
With SuperCollider, the paradigm shift you're looking for is to create SynthDefs as discrete entities:
s.waitForBoot ({
b = Bus.new('control');
SynthDef(\scissors, {arg bus;
var env;
env = EnvGen.kr(Env.linen);
//EnvGen.kr(Env.new([1,0.001],[1],curve: 'exp'), timeScale: 1, doneAction: 2);
Out.kr(bus, env);
}).add;
SynthDef(\oscillator, {arg bus, out=0, freq=440, amp = 0.1;
var oscillator, scissored;
oscillator = SinOsc.ar(freq,0,1);
scissored = oscillator * In.kr(bus) * amp;
Out.ar(out, scissored);
}).add;
s.sync;
Task({
Synth(\scissors, [\bus, b]);
s.sync;
10.do({|i|
Synth(\oscillator, [\bus, b, \freq, 100 * (i+1)]);
0.1.wait;
});
}).play
});
I've changed for a longer envelope and a change in pitch, so you can hear all the oscillators start.
What I've done is I've defined two SynthDefs and a bus.
The first SynthDef has an envelope, which I've lengthened for purposes of audibility. It writes the value of that envelope out to a bus. This way, every other SynthDef that wants to use that shared envelope can get it by reading the bus.
The second SynthDef has an a SinOsc. We multiply the output of that by the bus input. This uses the shared envelope to change the amplitude.
This "works", but if you run it a second time, you'll get another nasty surprise! The oscillator SynthDefs haven't ended and you'll hear them again. To solve this, you'll need to give them their own envelopes or something else with a doneAction. Otherwise, they'll live forever.Putting envelopes on each individual oscillator synth is also a good way to shape the onset of each one.
The other new thing you might notice in this example is the s.sync; lines. A major feature of SuperCollider is that the audio server and the language are separate processes. That line makes sure the server has caught up, so we don't try to use server-side resources before they're ready. This client/server split is also why it's best to define synthdefs before using them.
I hope that the long wait for an answer has not turned you off permanently. You may find it helpful to look at some tutorials and get started that way.

display a Simulink current simulation time

folks!
I am trying to display the Simulink current simulation time. I have to notice that, in my case, the system is not viewable, once I use load_system, and it would be very useful to know how progress the simulation.
For that, I have read that I should use the function 'ssGetT'. To implement it, I am using S-function builder block and I succeeded. I mean, I was able to get the current simulation time.
However, I am caught at this point, because I do not know how display it either a progress bar or a message box or any other way. Important, display from an C environment in S-function builder.
If there is any other way to do it, please me. =)
If anybody could help me, I would really appreciate it.
A couple of things to note:
There is no need to use load_system prior to using sim.
As with any MATLAB command, sim blocks further execution of m-code after that line in your m-code (or the command line) until it has finished executing (which in this case means that the simulation has stopped).
But any m-code within the model will definitely get excuted during model execution.
For instance, create a model where you feed the Clock block into a MATLAB Function block. Within the MATLAB Function block have the following code
function fcn(t)
%#codegen
coder.extrinsic('fprintf');
persistent firstTime
if isempty(firstTime)
firstTime = false;
fprintf('Starting Now\n');
end
fprintf('time = %.4f\n',t);
This will print the simulation time, at every time step, to the MATLAB Command Window, while the simulation is running (irrespective of how the model is started).
Updating...
To display a progress status in the commad view, I took Phil's suggestion.
I implemented this system in symulink in which the fcn inputs are the simulation time from a clock and the final simulation time.
I define SampleTime in the Digital Clock block as Final simulation time/steps, where steps is the number of time you want to update the progress. In my case, I update it at each 5% untill 100%, so steps is 20.
The fnc block is:
function fcn(t,tsim)
coder.extrinsic('fprintf');
persistent firstTime
if isempty(firstTime)
firstTime = false;
fprintf('\nSimulating...\n\n');
end
prog = 100*t/tsim;
fprintf(' %1.0f%%',prog);

Resources