i am trying to make a sniper rifle that shoot piercing bullet. by piercing bullet i mean that the bullet will pass through x number of enemies before stopping. i already made most of the gun script but now i am stuck at making piercing bullet.so my question is how can i make a piercing bullet?
i am currently using a raycast to shoot so my best guest is using layers but im not sure how.
Ther are two ways of doing that
- You could use RaycastAll to check for hits against all colliders but th order to array returned is not guarenteed
Eg Lets say you fire a weapon using RaycastAll it is going to cast a ray agains all colldiers.Consider a enemy behind a wall.The ray is first going to hit the wall then the enemy . BUT the array returned may not be the same that is it may say it first hit the enemy and then the wall
her si an example script
hits = Physics.RaycastAll (transform.position, transform.forward, 100.0f);
for(RaycastHit hit in hits )
2. Other way around is much more complex you could create an empty GameObject which keeps on casting a ray in forward direction to it.(The GameObject should not have a colldier attached to it).And you could send the gameObject in the direction which you fire
Or you could check for collision using a single Raycast and then cast another ray from that hit position
This is what I used to ensure I could hit all the targets between my source and the nearest blocking surface.
float maxPierceDistance = 100f;
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out blockHit, maxPierceDistance, LayerMask.GetMask("Cover")))
maxPierceDistance = blockHit.distance;
RaycastHit hit = Physics.RaycastAll(ray, maxPierceDistance, LayerMask.GetMask("Enemy"));