Shooting on PlayCanvas

Hi, i’m new here and my question is:

How do i something shoot?

1 Like

EDIT:
I don’t have time to go sift through the API for you however what I will do is help you step through the logic of what you want to achieve.

So you want to make a gun shoot a bullet in a given direction. Let’s break this down into steps that should occur for this to happen.

When you think about it, in real life to have this all happen you will need to do these steps:

1. Have a gun.
2. Aim the gun.
3. Pull the trigger.
4. Fire a bullet in the direction of the aim.
5. Bullet should stop when it hits an object.

So how to we translate that into a game? We have to break it down a little bit more as well as fake a few things. So to begin lets start with:

1. Have a gun; The first thing you’re going to have to do is to have an entity in the game that is acting as your gun.
2. Aim the gun; This is where it’s going to be a little bit more challenging if you’re new to programming. You’re now needing to aim the gun in a direction. This is different when your designing a game to be either first person, third person, or both. You will need to work out some basic trig calculations and some vector calculations.
So to break this step up you will need to:
1. Hard option, firing the bullet out of the barrel:
1. A spot to aim at; In 3D you will need a vector from the barrel of you gun to a point in space in front of your gun.
2. Have this 3D vector controlled by a 2D input (your mouse). So you’ll need to set the local rotation of the gun using euler angles. but only interpret the x, y coordinates. You will also need to line up the gun with the crosshair which means you need to account of the parallax, in other words just aim to infinite and you should be a-okay.
2. Easy option, shoot out of the character’s origin:
1. If your setting this up to be an FPS, you’ve already got mouselook working.
2. Take a vector from the camera’s forward direction and use that as aim. Don’t apply it to your gun.
3. Pull the trigger; this is the easiest step, just listen for a mouse click event or any other event you want to have happen. This event should then trigger the next step.
4. Fire the bullet in the direction of the aim; you will have to instance an entity at the barrel of your gun and then apply a force vector to it (a force and a direction (the direction can be attained from the aim vector)).
5. Detect a collision between your bullet and an object with collision enabled.

Have a look at: https://developer.playcanvas.com/en/tutorials/first-person-movement/ for FPS based mouselook which shows you how to convert your mouse input into eurler angles.