private void Shoot() { --_currentAmmo; _UI.UpdateAmmo(_currentAmmo); if (_shootingSoundSource.isPlaying == false) { _shootingSoundSource.Play(); } _muzzleFash.Emit(1); _laserStreaks.Emit(1); Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0)); // I can also use ScreenPointToRay and pass the mouse position on screen as a parameter RaycastHit hitInfo; if (Physics.Raycast(ray, out hitInfo, Mathf.Infinity)) { Debug.Log("Raycast hit the Gameobject with a collider box named: " + hitInfo.transform.name); _hitMarkerContainer = Instantiate(_hitMarkerPrefab, hitInfo.point, Quaternion.LookRotation(hitInfo.normal)); Destroy(_hitMarkerContainer, 5.0f); Crate crate = hitInfo.transform.GetComponent <Crate>(); if (crate != null) { crate.DestroyCrate(); } } else { Debug.Log("I hit nothing"); } }
private void Shoot() { _currentBullets--; //update the number of bullets in UI UpdateBulletsUI(); //we will use ViewportPointToRay, because it allows us to values from 0-1 for the Vector position //0.5 being the center Ray originOfShot = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0)); RaycastHit hitInfo; if (Physics.Raycast(originOfShot, out hitInfo)) { //hitInfo.point is the position of the target //LookRotation will let us choose the rotations, and using hitInfo.normal we get the normal/perpendicular of the target //we will TypeCast it as a GameObject, so we can destroy it later on, without having to make a script for it. GameObject hitMarkObj = Instantiate(_hitMarker, hitInfo.point, Quaternion.LookRotation(hitInfo.normal)) as GameObject; GameObject.Destroy(hitMarkObj.gameObject, 1.2f); //Shooting a crate //hitInfo is just a container for the gameObject, that is why we use hitInfo.transform before Getting component Crate crate = hitInfo.transform.GetComponent <Crate>(); if (crate != null) { crate.DestroyCrate(); } } if (!_shootingSound.isPlaying) { _shootingSound.Play(); } _muzzleFlash.SetActive(true); }