Gun won't shoot bullets/ projectiles

Hi I am a student currently trying to code an FPS game and the gun isn’t shooting any bullets. It was working at first, and then I added a collision for the bullets to destroy the enemies, and created new scenes and added a switch scene code. Now the gun isn’t working

when I start up the game it only says “403” as an error

then when I make the fps character collide with the Dad (the character with the blue shit) which is supposed to lead the Mission Complete or “End Scene”

image

and go through all the scene changes and make it back to the main scene, an error pops up later on when I try to left click to shoot saying this

Here is the entire code for our FPS movement which should include charactermovement, camera things and also the gun

var FirstPersonMovement = pc.createScript('firstPersonMovement');

FirstPersonMovement.attributes.add('camera', {type: 'entity'});
FirstPersonMovement.attributes.add('power', {type: 'number', default: 2500 });
FirstPersonMovement.attributes.add('lookSpeed', {type: 'number',default: 0.25});

// ------ gflopez section -----------------------------------------------------
    FirstPersonMovement.attributes.add('gunEntity', {type: 'entity'});
    FirstPersonMovement.attributes.add('bulletPower', {type: 'number'});
// ----------------------------------------------------------------------------

// initialize code called once per entity
FirstPersonMovement.prototype.initialize = function() {
    this.force = new pc.Vec3();
    this.eulers = new pc.Vec3();

    var app = this.app;

    // Listen for mouse move events
    app.mouse.on("mousemove", this._onMouseMove, this);

    // when the mouse is clicked hide the cursor
    app.mouse.on("mousedown", function () {
        app.mouse.enablePointerLock();

        // ------ gflopez section --------------------------------------------------
            this.gflopez();
        // -------------------------------------------------------------------------
    }, this);

    // Check for required components
    if (!this.entity.collision) {
        console.error("First Person Movement script needs to have a 'collision' component");
    }

    if (!this.entity.rigidbody || this.entity.rigidbody.type !== pc.BODYTYPE_DYNAMIC) {
        console.error("First Person Movement script needs to have a DYNAMIC 'rigidbody' component");
    }
};

// update code called every frame
FirstPersonMovement.prototype.update = function(dt) {
    // If a camera isn't assigned from the Editor, create one
    if (!this.camera) {
        this._createCamera();
    }

    var force = this.force;
    var app = this.app;

    // Get camera directions to determine movement directions
    var forward = this.camera.forward;
    var right = this.camera.right;


    // movement
    var x = 0;
    var z = 0;

    // Use W-A-S-D keys to move player
    // Check for key presses
    if (app.keyboard.isPressed(pc.KEY_A) || app.keyboard.isPressed(pc.KEY_Q)) {
        x -= right.x;
        z -= right.z;
    }

    if (app.keyboard.isPressed(pc.KEY_D)) {
        x += right.x;
        z += right.z;
    }

    if (app.keyboard.isPressed(pc.KEY_W)) {
        x += forward.x;
        z += forward.z;
    }

    if (app.keyboard.isPressed(pc.KEY_S)) {
        x -= forward.x;
        z -= forward.z;
    }

    // use direction from keypresses to apply a force to the character
    if (x !== 0 || z !== 0) {
        force.set(x, 0, z).normalize().scale(this.power);
        this.entity.rigidbody.applyForce(force);
    }

    // update camera angle from mouse events
    this.camera.setLocalEulerAngles(this.eulers.y, this.eulers.x, 0);
};

FirstPersonMovement.prototype._onMouseMove = function (e) {
    // If pointer is disabled
    // If the left mouse button is down update the camera from mouse movement
    if (pc.Mouse.isPointerLocked() || e.buttons[0]) {
        this.eulers.x -= this.lookSpeed * e.dx;
        this.eulers.y -= this.lookSpeed * e.dy;
    }
};

FirstPersonMovement.prototype._createCamera = function () {
    // If user hasn't assigned a camera, create a new one
    this.camera = new pc.Entity();
    this.camera.setName("First Person Camera");
    this.camera.addComponent("camera");
    this.entity.addChild(this.camera);
    this.camera.translateLocal(0, 0.5, 0);
};

// user-defined function - gflopez section -----------------------------------
FirstPersonMovement.prototype.gflopez = function(dt){

    if(GameManager.instance.defaultAmmo <= 0){
        return;
    }

    // step-1 get the center of the screen
    var centerScreenX = this.app.graphicsDevice.width/2;
    var centerScreenY = this.app.graphicsDevice.height/2;

    // step-2 get the start and end point
    var start = this.camera.camera.screenToWorld(centerScreenX, centerScreenY, this.camera.camera.nearClip);
    var end = this.camera.camera.screenToWorld(centerScreenX, centerScreenY, this.camera.camera.farClip);

    // step-3 trigger raycast between two points and return the closest hit result
    var result = this.app.systems.rigidbody.raycastFirst(start, end);

    if(result){
        switch (result.entity.name){
            case "enemyBox1":
                if((GameManager.instance.defaultHealth1 -=1) ==0){
                    result.entity.destroy();
                };
            break;
            case "enemyBox2":
                if((GameManager.instance.defaultHealth2 -=1) ==0){
                    result.entity.destroy();
                };
            break;
            case "enemyBox3":
                if((GameManager.instance.defaultHealth3 -=1) ==0){
                    result.entity.destroy();
                };
            break;
        };
        GameManager.instance.defaultAmmo -=1;
    };

    // step-4 set the bullet asset, identify the gunEntity, apply force and create instance

        // step-4.1 bullet asset
        var bulletAsset = this.app.assets.get(173459041);

        // step-4.2 create the instance of the bullet
        var bulletInstance = bulletAsset.resource.instantiate();

        // step-4.3 add to hierarchy
        this.app.root.addChild(bulletInstance);

        // step-4.4 identify the gun and set the force
        var gun = this.gunEntity;

        this.force = new pc.Vec3();
        this.force.copy(gun.forward);
        this.force.scale(this.bulletPower);

        var pos = gun.getPosition();
        bulletInstance.setPosition(pos);
        bulletInstance.enabled = true;
        bulletInstance.rigidbody.applyImpulse(this.force);
};

I am not sure what’s the problem, if the scene changes are causing anything or if there’s something Im not noticing. I would greatly appreciate the help

Here is the link for our playcanvas game

https://playcanvas.com/editor/scene/1977990

Hi @chiyopot!

This is probably because an issue with one of your assets. I suggest to remove it.

This is probably because there is an event listener active when you click the mouse. Because not all requirements are available in the menu scene you get the error. You need to clean up the events manually.

image

Hey!

Okay thank you for answering!

Sorry to ask because I’m not that highly knowledgeable on this stuff but how do I clean up the events manually?

Where you create the event you also need to add something like below (not sure if it is totally correct).

this.on('destroy', function() {
    app.mouse.off("mousedown", function () {
        app.mouse.enablePointerLock();
        this.gflopez();
    }, this);
});

You need to do this for every event you create.

hi! so if I were to add in this new line of code, where would I have to place it?

Not sure what you mean with that line of code.

Currently you execute that line of code with an event you have created in the initialize function. You also need to add my code suggestion in the initialize function. This will stop the event when the script is destroyed (for example because you changed the scene).