I’m creating a twin-stick mobile game and I’ve came to the point, where I need to implement weapon shooting mechanics.
I have AimComponent class, which is attached to weapon prefab. This class has method GetAimTarget, which returns object, that my gun is currently pointing.
[SerializeField] private Transform _weaponMuzzle;
[SerializeField] public float _aimRange = 1000;
[SerializeField] private LayerMask _aimMask;
public GameObject GetAimTarget()
{
Vector3 aimStart = _weaponMuzzle.position;
if (Physics.Raycast(aimStart, GetAimDirection(), out RaycastHit hit, _aimRange, _aimMask))
{
return hit.collider.gameObject;
}
return null;
}
private Vector3 GetAimDirection()
{
Vector3 muzzleDirection = _weaponMuzzle.forward;
return new Vector3(muzzleDirection.x, 0f, muzzleDirection.z).normalized;
}
The problem is that RaycastHit hit always returns null, wherever I shoot.
_aimMask variable is set to Everything in editor. _weaponMuzzle is a transform of child object of Rifle prefab (Screenshot_1). It’s not colliding with weapon collider simply beacause weapon prefab has no collider. I’ve tried to debug ray with OnDrawGizmos method:
private void OnDrawGizmos()
{
Debug.DrawRay(_weaponMuzzle.position, _weaponMuzzle.position + GetAimDirection() * _aimRange, Color.red);
}
And it seems to be perfectly fine - ray is pointing at desirable direction (Screenshot_2). The objects I shoot at have collider. What can be the problem?