Shooting when touching crosshair

Since doing real bullets is far too difficult even after looking at many examples. I want to make it when you are shooting and the cross hair is touching a target and it not hiding behind a wall or anything it will take damage. Can I do that or is there an easy way to make bullets?
https://playcanvas.com/editor/scene/1669040

Doesn’t seem very sensible to me either…

I think you are looking for raycasting. That’s basically an invisible line between two points. You can check what is at the end of the line.

https://developer.playcanvas.com/en/user-manual/physics/ray-casting/

I get the concept but how do I make it start at the camera and detect what it hits?

@Brent_Reddick You could have a look to the gunshoot.js script in this project as suggested before. It will show how the raycast is setup from the camera view.

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

// handle shooting and raycast
GunShoot.prototype.shoot = function(e) {

    // Get center of screen
    var centerScreenX = this.app.graphicsDevice.width / 2;
    var centerScreenY = this.app.graphicsDevice.height / 2;

    //Get 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);
    
    // raycast between the two points and return the closest hit result
    var result = this.app.systems.rigidbody.raycastFirst(start, end);

    // Play and reset muzzle flash
    this.muzzleFx.particlesystem.play();
    this.muzzleFx.particlesystem.reset();

    if(this.entity.sound != null) {
        // Play this weapons sound
        this.entity.sound.play("fire");
    }

    // We hit something with collision
    if(result) {

        console.log("You Hit: " + result.entity.name);
        this.handleImpact(result.entity,result.point,result.normal);
 
    } else {

        console.log("Nothing Hit");
    }

};
2 Likes

I tried puting it in but I am getting an error, do you know the issue? PlayCanvas | HTML5 Game Engine

@Brent_Reddick If you click on the yellow text link you will be taken directly to the error in your code. I am not sure what the issue is currently. Is it possible you don’t have the camera entity link in your code. You could take a look at the example gun-shoot.js to see how it is done.

@Brent_Reddick I see that you have two cameras one under another. I don’t think this will work well

image

the second camera is to render the gun so it does not go through walls

It seems that you already solved this problem?

no I need the gun to fire bullets using either cloning or ray casts, I prefer casting but I am finding it difficult to learn even after the tutorial