[SOLVED] Enabling Sprite on Mouse down

Hello All!

I am recreating “Doom” on Playcanvas, and I’m looking to add a gun fire effect true to the original version.
I have created a script that is supposed to enable a sprite in front of the player’s gun, but it gives me an error. Does anyone have any idea of what’s wrong, and what I should do to get this to function?



@RumaiIndustries It looks like from the screen shots that the sprite you are trying to enable is a child of the camera entity of which the script it is attached to and not a attribute of the this.entity itself. I don’t know if this will help you or not but you could have a look at how I did this here:

https://playcanvas.com/project/990658/overview/weapontest

Instead of attributes you can also use findByName. With this you can find and enable a child entity or another entity in your scene.

this.entity.findByName('Name').enabled = true;
this.app.root.findByName('Name').enabled = true;

https://developer.playcanvas.com/api/pc.Entity.html#findByName

2 Likes

Thank you so much, both of you!

@Albertos, this worked well, is there a way to wait a second and then disable it again?

Thank you in advance!

I think it should be something like below.

var Example = pc.createScript('example');

// initialize code called once per entity
Example.prototype.initialize = function() {
    this.sprite = this.entity.findByName('Name');
    //this.sprite = this.app.root.findByName('Name');

    this.timer = 0;
    this.timerActive = false;
};

// update code called every frame
Example.prototype.update = function(dt) {
    if (this.app.mouse.isPressed(pc.MOUSEBUTTON_LEFT)) {
        this.timerActive = true;
    }

    if (this.timerActive) {
        this.timer += dt;
        this.sprite.enabled = true;

        if (this.timer > 1) {
            this.timer = 0;
            this.timerActive = false;
            this.sprite.enabled = false;
        }
    }
};

1 Like

That was so simple, I can’t believe I didn’t think of that.

Thank you so much @Albertos, It worked perfectly!

2 Likes