2.5D Bullet hitbox detection for distant objects

Hello, I am not even sure how to ask it properly so I will just give you an example

15:28


As you can see, the robot is behind the dude, but his bullets still hit it. I want to achieve this same exact thing, 2.5D with full 3D environments and create bullets that hit anything no matter how close or far away from the camera they are. I have really no idea how to achieve this and if you could provide some code I would be very grateful.

Thank you

Hi @unixty,

A good way to achieve what you want is using Raycast. If you Raycast from your bullet position and in the direction the camera is facing, you can detect if your bullet hit some enemy, regardless of how far away from the camera it is.

Below there is a example situation:

In this situation the Character has fired a bullet upwards and using a Raycast, a collision was detected between the bullet and the enemy.

Below there is a sample code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bullet : MonoBehaviour
{
    public int damage;
    public float rayCastDistance;
    public LayerMask targetsLayerMask;

    void Start ()
    {
		// Some initializantion code
	}

    void Update ()
    {
        RaycastHit hitInfo;

        //If the raycast hit something, the bullet must try to apply damage
        if (Physics.Raycast(transform.position, Camera.main.transform.forward, out hitInfo, rayCastDistance, targetsLayerMask))
        {
            HealthComponent hc = hitInfo.transform.GetComponent<HealthComponent>();

            //If the GameObject hit by the ray has a HealthComponent it must receive damage
            if (hc)
            {
                //The bullet applies damage to the enemy
                hc.TakeDamage(damage);

                //Destroy the bullet after applying the damage
                Destroy(gameObject);
            }
        }

        //Drawn the raycast in the Scene View
        Debug.DrawLine(transform.position, transform.position + (Vector3.forward * rayCastDistance), Color.red);
	}
}

In the “distance” variable, you just have to put a high value, in order to ensure that the bullet will hit any thing that is faaaarrrrrrrr away from the camera. But remember that Raycast is performance expensive, so the shorter the distance of the ray the better the performance.

In the “targetsLayerMask” variable you select the layers with which the bullet should collide.

If you also want to check if the bullet is colliding with a enemy that is between the bullet and the camera, you just need to create another Raycast in the opposite direction of the one I’ve shown in the exemple image.