I'm working on a fps for fun and am attempting to implement bullet spread.
my raycast is defined with
if(Physics.Raycast(playercam.transform.position, playercam.transform.forward, out hit))
I figured it would work by doing something like
if(Physics.Raycast(playercam.transform.position, playercam.transform.forward new Vector3(*random numbers*), out hit))
(I don't remember the function for random number but it's not important)
but even trying to get this to function returns no good results.
Is it just my implementation or is there a better way?
CodePudding user response:
To add spread to the above code, you can generate a random direction vector within a cone centred around the camera's forward direction and then use that direction vector as the direction for the raycast.
#region Serialized Fields
[SerializeField] [Range(0, 20)] private float spreadAngle = 10.0f;
#endregion
private Camera _playerCamera;
private Vector3 _randomDirection;
#region Event Functions
private void Awake()
{
_playerCamera = Camera.main;
}
private void OnDrawGizmosSelected()
{
if (!Application.isPlaying) return;
// Draw the spread cone and the resulting raycast direction
var cameraTransform = _playerCamera.transform;
var cameraPosition = cameraTransform.position;
Gizmos.color = Color.red;
Gizmos.DrawLine(cameraPosition,
cameraPosition cameraTransform.forward * 100.0f);
Gizmos.color = Color.green;
Gizmos.DrawLine(cameraPosition, cameraPosition _randomDirection * 100.0f);
}
#endregion
public void Shoot()
{
_randomDirection = Random.insideUnitSphere;
_randomDirection = Vector3.Slerp(_playerCamera.transform.forward, _randomDirection, spreadAngle / 180.0f);
if (Physics.Raycast(_playerCamera.transform.position, _randomDirection, out var hit))
Debug.Log(hit.collider.name);
}
The above code generates a random direction vector within a cone centred around the camera's forward direction, using the Random.insideUnitSphere
property and the Vector3.Slerp()
method. The maximum spread angle is defined by the spreadAngle
variable and is used to control the size of the spread cone. You could extend this to use Unity's