I have searched up so many sites on Google to try and get this to work but NO ONE seems to have this anywhere , and if they do it's just NOT working with my program... What I am trying to achieve is to have a player recoil that when the player gets hit, he has a "x" amount of time between getting hit the first time and the second time.
So I have a Boolean "hit" = false and when he gets hit, it changes to true. Which means he can't get hit again until it's changed to false again.
So I'm trying to set up a function in my program to set a "timer" for "x" amount of seconds IF hit = true and once that timer hits "x" amount of seconds, hit will get switched back to false.
Anyone have any ideas?
Thanks!!
A simple option is to manually keep track of time using millis().
You would use two variables:
one to store elapsed time
one to store the wait/delay time you need
In the draw() method you would check if the difference between the current time (in millis.) and the previously stored time is greater(or equal) to the delay.
If so, this would be your cue to do whatever based on the delay chosen and update the stored time:
int time;
int wait = 1000;
void setup(){
time = millis();//store the current time
}
void draw(){
//check the difference between now and the previously stored time is greater than the wait interval
if(millis() - time >= wait){
println("tick");//if it is, do something
time = millis();//also update the stored time
}
}
Here's a slight variation the updates a 'needle' on screen:
int time;
int wait = 1000;
boolean tick;
void setup(){
time = millis();//store the current time
smooth();
strokeWeight(3);
}
void draw(){
//check the difference between now and the previously stored time is greater than the wait interval
if(millis() - time >= wait){
tick = !tick;//if it is, do something
time = millis();//also update the stored time
}
//draw a visual cue
background(255);
line(50,10,tick ? 10 : 90,90);
}
Depending on your setup/needs, you may choose to wrap something like this into a class that can be reused. This is a basic approach and should work with the Android and JavaScript versions as well (although in javascript you've got setInterval()).
If you're interested in using Java's utilities, as FrankieTheKneeMan suggested, there is a TimerTask class available and I'm sure there are plenty of resources/examples out there.
You can run a demo bellow:
var time;
var wait = 1000;
var tick = false;
function setup(){
time = millis();//store the current time
smooth();
strokeWeight(3);
}
function draw(){
//check the difference between now and the previously stored time is greater than the wait interval
if(millis() - time >= wait){
tick = !tick;//if it is, do something
time = millis();//also update the stored time
}
//draw a visual cue
background(255);
line(50,10,tick ? 10 : 90,90);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.4/p5.min.js"></script>
Related
I have come across a situation where if Time.time is called at two different places at different passes in Update() the value will differ
in its increment thus any use of Vector3(0,Time.time,0) will cause
jumps in the results. I have a gameobject that starts a path in
section of code then transitions to another set of code further along
in the script. The gap execution of Time.time in the first call and
the second call is different than the gaps in the loop of the first
call. That is why I am asking about a replacement. Its not about the code. Its about the Time.time variance between the two Time.time usages. I believe there is an execution caused variance.
void Update () {
synchTime = Time.time;
// This proc releases gameobject from center into an outward spiralling trajectory till the height orbit path attained,
// then disables itself releasing the gameobject into the sine wave orbital path.
if (!reachedElevation)
{
transform.Translate(0, Time.deltaTime, 0);
reachedElevation = true;
_AgentY = Mathf.Sin(synchTime);//Keeps value started and in synch with usage below
}else{
// The trouble is making the 'Y' synch between where the spiral left off and this sine. It has to do with Time.time
_AgentY = Mathf.Sin(synchTime);
Debug.Log("Before transform.localPosition.y: " + transform.localPosition.y);
transform.localPosition = new Vector3(transform.localPosition.x, _AgentY, transform.localPosition.z);
Debug.Log("After transform.localPosition.y: " + transform.localPosition.y);
}
}
Create a local variable at the start of the update call, and set it to Time.time, then you can reference this variable anywhere within the update and it will remain the same.
I Been messing with Actionscript 2 for about 2 days.. And i have not learned much as im blindly going along with it... But i wrote a function and im curious as to why its not working.. So can someone tell me whats wrong with this code , or even if it could work?
function Interval(Funct:Function, Seconds:Number, Duration:Number){
var MyInterval:Number;
Seconds = Seconds * 1000;
MyInterval = setInterval(Funct, Seconds, Duration);
if(Seconds >= Duration * 1000)
{
clearInterval(MyInterval);
}
return MyInterval;
}
Problem Solved , Solution Below :
function Interval(Funct:Function, Seconds:Number){
Seconds = Seconds * 1000;
_global.i = setInterval(Funct, Seconds);
}
Even though i did want a limit as to when it would stop if specified , im okay with this for now
Thank you Ali-o-kan
Edit : Ran into another problem with this function.. Whenever i enable it more than once using different keys , it leaves it on while creating more whenever i press the button again.. Any way to fix this?
Has anyone been able to loop a MIDI file without problems on IOS9 Beta?
As soon as I try to loop by setting numberOfLoops to 0 in MusicTrackLoopInfo, it locks up the app by sending random MIDI to the player. I've reported it, but am wondering if anyone has found a work around. The same code works perfectly under all other iOS versions.
MusicTrackLoopInfo loopInfo;
loopInfo.loopDuration = loopLength;
loopInfo.numberOfLoops = 0;
OK I just heard iOS9 will ship with this bug in it. Terrible.
Here is a work around.
Don't set numberOfLoops at all, OR set numberOfLoops = 1; // means loop once
Now make a variable (i.e. myVariableToKeepTrackOfAddedCopies) that keeps track of the number of times you will actually perform the following:
In your MIDIReadProc at some point BEFORE the track has finished playing, do the following:
// Copy the track to itself - effectively doubling the length
MusicTrack theTrack=nil;
MusicTrackGetProperty(theTrack, kSequenceTrackProperty_TrackLength, &trackLen, &trackLenLen);
trackLen = 4.0; //<-- this is your real track length
MusicTrackCopyInsert(theTrack, 0, trackLen, theTrack, 0);
myVariableToKeepTrackOfAddedCopies++;
So now your track is twice as long before it ends and the track will continue. This will work the same as looping except you are taking up more memory since you are making the track length longer after each iteration.
When you stop the sequence/track, cut the track back to the original size.
MusicTrackCut(theTrack, 4.0, 4.0 + (4.0*myVariableToKeepTrackOfAddedCopies));
MusicTrackGetProperty(theTrack, kSequenceTrackProperty_TrackLength, &trackLen, &trackLenLen);
Irritating, but it works. I just verified on iOS9 beta 5. Hope it helps.
This is fixed as of iOS release 9.2
Oddly enough, the tempo track does not seem to have this problem. The following code does not lock up for me:
MusicTrack tempoTrack;
OSSTATUS = MusicSequenceGetTempoTrack(self.sequence, &tempoTrack);
SafeMusicTrackClear(tempoTrack); //calls into MusicTrackClear
MusicTrackNewExtendedTempoEvent(tempoTrack, 0, self.tempo * self.tempoMultiplier);
MIDIMetaEvent timeSignatureMetaEvent;
timeSignatureMetaEvent.metaEventType = 0x58;
timeSignatureMetaEvent.dataLength = 4;
timeSignatureMetaEvent.data[0] = 1;
timeSignatureMetaEvent.data[1] = 4;
timeSignatureMetaEvent.data[2] = 0x18;
timeSignatureMetaEvent.data[3] = 0x08;
MusicTrackNewMetaEvent(tempoTrack, 0, &timeSignatureMetaEvent);
MusicTrackLoopInfo loopInfo;
loopInfo.loopDuration = 0.25f;
loopInfo.numberOfLoops = 0;
MusicTrackSetProperty(tempoTrack, kSequenceTrackProperty_LoopInfo, &loopInfo, sizeof(loopInfo));
Unfortunately, it does not seem that the tempo track can actually play notes.
UPDATE:
After a few hours of digging around and trying to figure out a better solution to the problem, I settled on manually looping by sending a user event at the end of my sequence.
My sequence is created in a method...
-(void) loadPacketsForLoopingSequence {
SafeMusicTrackClear(loopingTrack); //calls into MusicTrackClear
// calculate timestampToPlaySequenceAt -- the starting point of the current sequence iteration, probably in the past, based on MusicPlayerGetTime and the length of the sequence -- here
// calculate timestampToPlayNextSequenceAt -- the starting point of the next sequence iteration, based on MusicPlayerGetTime and the length of the sequence -- here
// a single iteration of the notes get added to loopingTrack here, starting at timestampToPlaySequenceAt
MusicEventUserData event;
event.length = 1;
event.data[0] = 0xab; //arbitrary designation
// -0.5 to make sure we still have time to do the next step in the callback
MusicTrackNewUserEvent(loopingTrack, timestampToPlayNextSequenceAt - 0.5, &event);
}
...which is called again in the callback:
void sequenceCallback(void* inClientData,
MusicSequence inSequence,
MusicTrack inTrack,
MusicTimeStamp inEventTime,
const MusicEventUserData* inEventData,
MusicTimeStamp inStartSliceBeat,
MusicTimeStamp inEndSliceBeat) {
CSMidiMusicPlayer* musicPlayer = (CSMidiMusicPlayer*)inClientData;
[musicPlayer loadPacketsForLoopingSequence];
}
The callback has to be registered during sequence init using MusicSequenceSetUserCallback.
The -0.5 kludge could probably be eliminated altogether by examining the parameters in sequenceCallback and modifying loadPacketsForLoopingSequence to accept a parameter, but I haven't gotten that far yet.
I like this solution because it stays in MIDI time and doesn't modify the MIDI file in unexpected, stateful ways. (New notes basically get streamed in when you get close enough to a loop marker.)
my problem is that I have an Alarmmanager that shoudl go off every 60 minutes to a defined time.
This, however, is only working for the first time.
With every next hour passing by Alarmmanager delays its work for 2 or 3 minutes.
Here an example:
hour is set to 4 p. m.
minute is set to 32
timer is set to 60 minutes
Calendar timeOff9 = Calendar.getInstance();
timeOff9.set(Calendar.HOUR_OF_DAY, hour);
timeOff9.set(Calendar.MINUTE, minute);
am.setRepeating(AlarmManager.RTC_WAKEUP, timeOff9.getTimeInMillis(), timer*60000, pi);
Maybe someone knows why that is so?
I am using API level 15. As of documentation API 19 setRepeating == setInexactRepeating
Thank you very much!
You almost answered your own question by referring to the documentation.
API 19 did indeed infer calls to setRepeating would be treated as setInexactRepeating.
The way to handle this is to set a new alarm when you handle receiving an alarm (>= API 19).
e.g.
#SuppressLint("NewApi")
private void setAlarm(AlarmManager alarmManager, long time,
PendingIntent pIntent, boolean repeat) {
if (android.os.Build.VERSION.SDK_INT >= 19) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pIntent);
} else {
if (repeat) {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time,
AlarmManager.INTERVAL_DAY * 7, pIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pIntent);
}
}
}
And then when you receive alarm..
/***
* From version 19 (KitKat) notification that are set repeating aren't
* exact, so the notification needs to be scheduled again each time it is
* received
*/
private void scheduleNextNotification() {
if (android.os.Build.VERSION.SDK_INT < 19) {
return;
}
// set alarm that would have otherwise been repeating
}
Hey I am using GetUserMedia() to capture audio input from user's microphone. Meanwhile I want to put captured values into an array so I can manipulate with them. I am using the following code but the problem is that my array gets filled with value 128 all the time (I print the results in console for now), and I can't find my mistake. Can someone help me find my mistake?
//create a new context for audio input
context = new webkitAudioContext();
var analyser = null;
var dataarray = [];
getLiveInput = function() {
navigator.webkitGetUserMedia({audio: true},onStream,onStreamError);
};
function onStream(stream)
{
var input = context.createMediaStreamSource(stream);
analyser = context.createAnalyser();
var str = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteTimeDomainData(str);
for (var i = 0; i < str.length; i++) {
var value = str[i];
dataarray.push(value);
console.log(dataarray)
}//end for loop
}//end function
function onStreamError(e) {
console.error('Streaming failed: ', e);
};
The values returned from getByteTimeDomainData are 8 bit integers, from 0 to 255. 128, which is half way, basically means "no signal". It is the equivalent of 0 in PCM audio data from -1 to 1.
But ANYWAY - there are a couple problems:
First, you're never connecting the input to the analyser. You need input.connect(analyser) before you call analyser.getByteTimeDomainData().
The second problem isn't with your code so much as it's just an implementation issue.
Basically, the gotStream function only gets called once - and getByteTimeDomainData only returns data for 1024 samples worth of audio (a tiny fraction of a second). The problem is, this all happens so quickly and for such a short period of time after the stream gets created, that there's no real input yet. Try wrapping the analyser.getByteTimeDomainData() call and the loop that follows it in a 1000ms setTimeout and then whistle into your microphone as soon as you give the browser permission to record. You should see some values other than 128.
Here's an example: http://jsbin.com/avasav/5/edit