Pistol Cooldown and physical bullet

I want to implement a ball canon to my game. For that, I’ve planned the following features:

  1. It should have a cooldown feature that prevents me from shooting for like 2 seconds
  2. The ball should move as if you were to throw it (not straight in a direction, I want to let it bounce around in the levels). It needs to be shot out in the direction I look at.

I have some features implemented already. For those, I want to know if they are implemented correctly:

  1. Normally, the ball should despawn if it exists longer than 7.5 seconds
  2. Otherwise, if the ball has detected a collision it should despawn in 3 seconds and play a collision sound.

Here is my code so far:

var Bullet = pc.createScript('Bullet');

// initialize code called once per entity
Bullet.prototype.initialize = function() {
    this.entity.collision.on('collisionstart', this.onCollisionStart, this); 
    this.entity.collision.on('collisionend', this.onCollisionEnd, this);
};

// update code called every frame
Bullet.prototype.update = function(dt) {
    if (this.entity.enabled === true) {
        this.entity.translateLocal(0,0,-0.4);

        setTimeout(function(){
            this.entity.destroy();
        }.bind(this), 7500);
    }
};

Bullet.prototype.onCollisionStart = function (result) {
    if (result.other) {
        setTimeout(function(){
            this.entity.destroy();
        }.bind(this), 3000);
    }
};

I am grateful in advance for any help I can get.

Hi @SayHiToMePls,

So using setTimeout inside the update loop is a no no, since a new timeout will start on each and every frame.

In general setTimeout should be avoided since it will fire even when the window is minimized/ is not focused.

Here is a different way to keep track of time, that can easily work with the script update method:

1 Like

And what about the actual shooting?

Before I can add a cooldown timer, I need to get shooting working in the first place because it doesn’t work.
I used the code from thebosser24 to get a starting point and intended to work up until I get, what I had in mind. The problem now is that when I click, it creates a clone of the bullet, but it won’t move.

Do you still have access to my project? If yes, could you take a look please?

P.s.: For me, it’s about 10 pm right now. That means that I might only see your answer and answer myself in 12 hours