Hello guys! I’m pretty new to java script, and I need help on something. What I need to do, is to make something happen in my function(dt) loop every 1 second. Thank you so much!!!
Can someone please help, this is super important to my game! It would mean the world to me if I got help!
The rough algorithm is as follows:
- Create a variable to store deltaTime and add deltaTime to the variable each time it updates.
- When the variable’s value exceeds 1000, execute the desired code, and then reset it to 0.
In addition, JavaScript also has the setInterval
function.
So something like this:
var Insanity = pc.createScript(‘insanity’);
var sanity = 0;
var deltaTime = 0;
// initialize code called once per entity
Insanity.prototype.initialize = function() {
};
Insanity.prototype.update = function(dt) {
deltaTime = deltaTime + 1;
if (deltaTime === 1000) {
console.error(‘test’);
deltaTime = 0;
}
};
In update function, it’s not guaranteed calling per every 1 millisecond.
What you need to do is comparing the previous timestamp and the current timestamp.
If 1 second passed, run your code.
PlayCanvas provides an update function with deltaTime already processed in milliseconds,
so the code can be as follows:
Movement.prototype.initialize = function() {
this.delta = 0;
};
// update code called every frame
Movement.prototype.update = function(dt) {
this.delta = this.delta + dt;
if (this.delta >= 1) {
console.log(this.delta);
this.delta = 0;
}
}
Oooooh ok, I understand now. Thank you guys for your time!!