Bullet Spread

For bullet firing I used Raycasts. Before I call the 'Physics.Raycast' function I calculate the 'startPosition' and 'direction' for the raycast. The 'startPosition' is the cameras position and the 'direction' is the front face of the camera added with the offset angle. The angle depends on the current 'burst count' - the amount of bullets fired in that 'burst'. It takes the value from a 'm_SpreadAngles' list which contains a realistic recoil pattern.


Vector2 spread = m_SpreadAngles[Mathf.Min(m_BurstCount, (m_SpreadAngles.Length - 1))];
Transform camera = Camera.main.transform;
Vector3 startPosition = camera.position;
Vector3 direction = camera.forward;
Vector3 offset = new Vector3(Mathf.Tan(spread.x), Mathf.Tan(spread.y), 0);
direction += camera.InverseTransformDirection(offset);
direction.Normalize();
RaycastHit hit;
if (Physics.Raycast(startPosition, direction, out hit, m_Range))
 {
  //Hit
 }

Mouse movement

The mouse 'update' function is called every frame. It first takes the X and Y values of the mouse, adds is to the 'XRotation' as well as the current recoil of the gun. The values are limited and then the camera and player are rotated.


void Update()
{
 float mouseX = Input.GetAxis("Mouse X") * m_Sensitivity * Time.deltaTime;
 float mouseY = Input.GetAxis("Mouse Y") * m_Sensitivity * Time.deltaTime;
 xRotation += -mouseY + xRecoil;
 xRotation = Mathf.Clamp(xRotation, -90f, 90f);
 transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
 m_PlayerBody.Rotate(Vector3.up * mouseX);
}

Hit marker

When the user fires and collides with an enemy a 'hit marker' game object is created. The parent is set to the canvas so it appears on the users screen correctly. If the enemy dies from that bullet the image colour is set to red, if not - the colour is set to white.


if (m_HitMarkerGO != null)
{
 Destroy(m_HitMarkerGO.gameObject);
}
m_HitMarkerGO = (GameObject)Instantiate(m_HitMarker);
m_HitMarkerGO.transform.SetParent(m_Canvas.transform);
if(personType == "Enemy")
{
 if (hit.transform.gameObject.GetComponent().GetHealth() - damage <= 0)
 {
  m_HitMarkerGO.GetComponent().color = Color.red;
 }
 else
 {
  m_HitMarkerGO.GetComponent().color = Color.white;
 }
}
				

Grenade throwing

When the function is called, the 'rigid body' component is referenced and a force is added to the grenade obeject in the scene. The 'AddForce' function takes in the vector direction and the 'ForceMode'.


private void ThrowGrenade()
{
 Rigidbody rigidBody = GetComponent();
 rigidBody.AddForce(transform.forward * m_ThrowForce, ForceMode.VelocityChange);
}

Feedback

TBA