void Start() { //set up object and component references playerObj = Camera.main.transform.GetComponent <CameraControl>().playerObj; myTransform = transform;//store this object's transform for optimization playerObjTransform = playerObj.transform; mainCameraTransform = Camera.main.transform; FPSPlayerComponent = playerObj.GetComponent <FPSPlayer>(); weaponObj = FPSPlayerComponent.weaponObj; MouseLookComponent = transform.parent.transform.GetComponent <SmoothMouseLook>(); GunSwayComponent = weaponObj.GetComponent <GunSway>(); FPSWalkerComponent = playerObj.GetComponent <FPSRigidBodyWalker>(); VisibleBodyComponent = FPSWalkerComponent.VisibleBody.GetComponent <VisibleBody>(); IronsightsComponent = playerObj.GetComponent <Ironsights>(); InputComponent = playerObj.GetComponent <InputControl>(); if (playerObj.GetComponent <WorldRecenter>()) { WorldRecenterComponent = playerObj.GetComponent <WorldRecenter>(); } AnimationComponent = GetComponent <Animation>(); offsetAmt = offset; currentDistance = 0f; zoomDistance = 0f; }
void Start() { //Set up external script references playerObj = Camera.main.transform.GetComponent <CameraControl>().playerObj; FPSWalkerComponent = playerObj.GetComponent <FPSRigidBodyWalker>(); IronsightsComponent = playerObj.GetComponent <Ironsights>(); CameraControlComponent = Camera.main.GetComponent <CameraControl>(); FootstepsComponent = playerObj.GetComponent <Footsteps>(); FPSPlayerComponent = playerObj.GetComponent <FPSPlayer>(); WeaponPivotComponent = FPSPlayerComponent.WeaponPivotComponent; }
void Start() { myTransform = transform;//store this object's transform for optimization playerObjTransform = playerObj.transform; mainCameraTransform = Camera.main.transform; //define external script references FPSWalkerComponent = playerObj.GetComponent <FPSRigidBodyWalker>(); IronsightsComponent = playerObj.GetComponent <Ironsights>(); FPSPlayerComponent = playerObj.GetComponent <FPSPlayer>(); WorldRecenterComponent = playerObj.GetComponent <WorldRecenter>(); }
void Start() { myTransform = transform; //define transform for efficiency //set up external script references FPSWalkerComponent = playerObj.GetComponent <FPSRigidBodyWalker>(); IronsightsComponent = playerObj.GetComponent <Ironsights>(); HorizontalBob = playerObj.GetComponent <HorizontalBob>(); FPSPlayerComponent = playerObj.GetComponent <FPSPlayer>(); InputComponent = playerObj.GetComponent <InputControl>(); CameraControlComponent = Camera.main.GetComponent <CameraControl>(); //initialize bobbing amounts walkBobYawAmount = Mathf.Clamp01(walkBobYawAmount); walkBobRollAmount = Mathf.Clamp01(walkBobRollAmount); sprintBobYawAmount = Mathf.Clamp01(sprintBobYawAmount); sprintBobRollAmount = Mathf.Clamp01(sprintBobRollAmount); gunBobRoll *= walkBobRollAmount; gunBobYaw *= walkBobYawAmount; }
void Start() { //set up component references if (CinemaCameraObj) { CinemaCameraObj.SetActive(false); } CameraControlComponent = MainCameraObj.GetComponent <CameraControl>(); MouseLookComponent = FPSCameraObj.GetComponent <SmoothMouseLook>(); FPSPlayerComponent = FPSPlayerObj.GetComponent <FPSPlayer>(); FPSWalkerComponent = FPSPlayerObj.GetComponent <FPSRigidBodyWalker>(); PlayerWeaponsComponent = FPSWeaponsObj.GetComponent <PlayerWeapons>(); IronsightsComponent = FPSPlayerObj.GetComponent <Ironsights>(); VisibleBodyComponent = FPSWalkerComponent.VisibleBody.GetComponent <VisibleBody>(); if (!FPSPlayerComponent.crosshairEnabled) { noCrosshair = true; //don't reactivate crosshair if it wasn't active to start } }
void Start() { GunSwayComponent = transform.parent.transform.GetComponent <GunSway>(); SmoothMouseLookComponent = GunSwayComponent.cameraObj.GetComponent <SmoothMouseLook>(); playerObj = Camera.main.transform.GetComponent <CameraControl>().playerObj; FPSPlayerComponent = playerObj.GetComponent <FPSPlayer>(); FPSWalkerComponent = playerObj.GetComponent <FPSRigidBodyWalker>(); InputComponent = playerObj.GetComponent <InputControl>(); PlayerWeaponsComponent = FPSPlayerComponent.PlayerWeaponsComponent; IronsightsComponent = FPSPlayerComponent.IronsightsComponent; PivotAnimComponent = GetComponent <Animation>(); myTransform = transform; childTransform = myTransform.GetChild(0); swayAmt = GunSwayComponent.swayAmount; if (deadzoneLooking) { SmoothMouseLookComponent.dzAiming = true; } }
void Start() { //set up component references if (CinemaCameraObj) { CinemaCameraObj.SetActive(false); } CameraControlComponent = MainCameraObj.GetComponent <CameraControl>(); FPSPlayerObj = CameraControlComponent.playerObj; FPSWeaponsObj = CameraControlComponent.weaponObj; FPSCameraObj = CameraControlComponent.transform.parent.transform.gameObject; MainCameraObj = Camera.main.transform.gameObject; MouseLookComponent = FPSCameraObj.GetComponent <SmoothMouseLook>(); FPSPlayerComponent = FPSPlayerObj.GetComponent <FPSPlayer>(); FPSWalkerComponent = FPSPlayerObj.GetComponent <FPSRigidBodyWalker>(); PlayerWeaponsComponent = FPSWeaponsObj.GetComponent <PlayerWeapons>(); IronsightsComponent = FPSPlayerObj.GetComponent <Ironsights>(); PlayerCharacterComponent = CameraControlComponent.PlayerCharacterComponent; PlayerCharacterObj = CameraControlComponent.PlayerCharacterObj; if (!FPSPlayerComponent.crosshairEnabled) { noCrosshair = true; //don't reactivate crosshair if it wasn't active to start } }
void Update() { //Set up external script references FPSRigidBodyWalker FPSWalkerComponent = playerObj.GetComponent <FPSRigidBodyWalker>(); Ironsights IronsightsComponent = playerObj.GetComponent <Ironsights>(); FPSPlayer FPSPlayerComponent = playerObj.GetComponent <FPSPlayer>(); CameraKick CameraKickComponent = Camera.main.GetComponent <CameraKick>(); Footsteps FootstepsComponent = playerObj.GetComponent <Footsteps>(); if (Time.timeScale > 0 && Time.deltaTime > 0) //allow pausing by setting timescale to 0 { waveslice = 0.0f; if (!FPSPlayerComponent.useAxisInput) { horizontal = FPSWalkerComponent.inputX; //get input from player movement script vertical = FPSWalkerComponent.inputY; } else { horizontal = FPSWalkerComponent.inputXSmoothed; //get input from player movement script vertical = FPSWalkerComponent.inputYSmoothed; } midpoint = FPSWalkerComponent.midPos; //Start bob from view position set in player movement script if (Mathf.Abs(horizontal) != 0 || Mathf.Abs(vertical) != 0 && FPSWalkerComponent.grounded) //Perform bob only when moving and grounded { waveslice = Mathf.Sin(timer); wavesliceRoll = Mathf.Sin(timerRoll); if (Mathf.Abs(FPSWalkerComponent.inputY) > 0.1f) { inputSpeed = Mathf.Abs(FPSWalkerComponent.inputY); } else { inputSpeed = Mathf.Abs(FPSWalkerComponent.inputX); } timer = timer + bobbingSpeed * inputSpeed * Time.deltaTime; timerRoll = timerRoll + (bobbingSpeed / 2.0f) * Time.deltaTime; //Make view roll bob half the speed of view pitch bob if (timer > Mathf.PI * 2.0f) { timer = timer - (Mathf.PI * 2.0f); if (!FPSWalkerComponent.noClimbingSfx) //dont play climbing footsteps if noClimbingSfx is true { FootstepsComponent.FootstepSfx(); //play footstep sound effect by calling FootstepSfx() function in Footsteps.cs } } //Perform bobbing of camera roll if (timerRoll > Mathf.PI * 2.0f) { timerRoll = (timerRoll - (Mathf.PI * 2.0f)); if (!FPSWalkerComponent.grounded) { timerRoll = 0; //reset timer when airborne to allow soonest resume of footstep sfx } } } else { //reset variables to prevent view twitching when falling timer = 0.0f; timerRoll = 0.0f; tempLocalEulerAngles = new Vector3(0, 0, 0); //reset camera angles to 0 when stationary } if (waveslice != 0) { translateChange = waveslice * bobbingAmount; translateChangePitch = waveslice * pitchingAmount; translateChangeRoll = wavesliceRoll * rollingAmount; translateChangeYaw = wavesliceRoll * yawingAmount; totalAxes = Mathf.Abs(horizontal) + Mathf.Abs(vertical); totalAxes = Mathf.Clamp(totalAxes, 0.0f, 1.0f); //needed for smooth return to neutral view pos translateChange = totalAxes * translateChange; translateChangePitch = totalAxes * translateChangePitch; translateChangeRoll = totalAxes * translateChangeRoll; //Set position for smoothing function and add jump value //divide position by deltaTime for framerate independence dampTo = midpoint + (translateChange / Time.deltaTime * 0.01f); //camera roll and pitch bob tempLocalEulerAngles = new Vector3(translateChangePitch, translateChangeYaw, translateChangeRoll); } else { if (!FPSWalkerComponent.swimming) { if (IronsightsComponent.cameraIdleBob) { idleYBob = Mathf.Sin(Time.time * 1.25f) * 0.015f; } } else { if (IronsightsComponent.cameraSwimBob) { idleYBob = Mathf.Sin(Time.time * 1.65f) * 0.08f; //increase vertical bob when swimming } } //reset variables to prevent view twitching when falling dampTo = midpoint + idleYBob; //add small sine bob for camera idle movement totalAxes = 0; translateChange = 0; } //use SmoothDamp to smooth position and remove any small glitches in bob amount dampOrg = Mathf.SmoothDamp(dampOrg, dampTo, ref dampVelocity, 0.1f, Mathf.Infinity, Time.deltaTime); //Pass bobbing amount and angles to the camera kick script in the camera object after smoothing CameraKickComponent.dampOriginY = dampOrg; CameraKickComponent.bobAngles = Vector3.SmoothDamp(CameraKickComponent.bobAngles, tempLocalEulerAngles, ref dampVelocity2, 0.1f, Mathf.Infinity, Time.deltaTime); } }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Select Weapons ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public IEnumerator SelectWeapon(int index) { FPSRigidBodyWalker FPSWalkerComponent = playerObj.GetComponent <FPSRigidBodyWalker>(); //we are not dropping a weapon anymore if one has been selected dropWeapon = false; //do not proceed with selecting weapon if player doesn't have it in their inventory //but make an exception for the null/unarmed weapon for when the player presses the holster button //also dont allow weapon switch if player is climbing, swimming, or holding object and their weapon is lowered if ((!weaponOrder[index].GetComponent <WeaponBehavior>().haveWeapon&& index != 0) || FPSWalkerComponent.hideWeapon) { yield break; } if (index != 0) //if a weapon is selected, prevent unarmed/null weapon from being selected in selection cycle { weaponOrder[0].GetComponent <WeaponBehavior>().haveWeapon = false; } //set up external script references Ironsights IronsightsComponent = playerObj.GetComponent <Ironsights>(); CameraKick CameraKickComponent = Camera.main.GetComponent <CameraKick>(); FPSPlayer FPSPlayerComponent = playerObj.GetComponent <FPSPlayer>(); WeaponBehavior CurrentWeaponBehaviorComponent = weaponOrder[currentWeapon].GetComponent <WeaponBehavior>(); //cancel zooming when switching FPSPlayerComponent.zoomed = false; //reset non-magazine reload if interrupted by weapon switch if (CurrentWeaponBehaviorComponent.bulletsToReload != CurrentWeaponBehaviorComponent.bulletsPerClip && CurrentWeaponBehaviorComponent.weaponMesh.GetComponent <Animation>()["Neutral"] && IronsightsComponent.reloading) { //play neutral animation when putting weapon away to prevent neutral anim glitch at start of next reload CurrentWeaponBehaviorComponent.weaponMesh.GetComponent <Animation>()["Neutral"].speed = 1.5f; CurrentWeaponBehaviorComponent.weaponMesh.GetComponent <Animation>().Play("Neutral", PlayMode.StopAll); //reset bulletsReloaded to prevent delay of reloading the next time we reload this weapon CurrentWeaponBehaviorComponent.bulletsReloaded = 0; } //cancel reloading when switching IronsightsComponent.reloading = false; //set IronSights Reloading var to false CurrentWeaponBehaviorComponent.StopCoroutine("Reload"); //stop the Reload function if it is running //make timer active during switch to prevent shooting switchTime = Time.time - Time.deltaTime; if (Time.timeSinceLevelLoad > 2) { //play weapon switch sound if not the first call to this function after level load AudioSource.PlayClipAtPoint(changesnd, mainCamTransform.position); //play camera weapon switching animation Camera.main.GetComponent <Animation>().Rewind("CameraSwitch"); Camera.main.GetComponent <Animation>().CrossFade("CameraSwitch", 0.35f, PlayMode.StopAll); } //if weapon uses rifle sprinting animation, set speed and play animation if (!CurrentWeaponBehaviorComponent.PistolSprintAnim) { //animate previous weapon down if (!FPSWalkerComponent.canRun) { weaponOrder[currentWeapon].GetComponent <Animation>()["RifleSprinting"].normalizedTime = 0; weaponOrder[currentWeapon].GetComponent <Animation>()["RifleSprinting"].speed = 1.5f; weaponOrder[currentWeapon].GetComponent <Animation>().CrossFade("RifleSprinting", 0.00025f, PlayMode.StopAll); } else { //if player is sprinting, keep weapon in sprinting position during weapon switch weaponOrder[currentWeapon].GetComponent <Animation>()["RifleSprinting"].normalizedTime = 1; } } else //weapon uses pistol sprinting animation //animate previous weapon down { if (!FPSWalkerComponent.canRun) { weaponOrder[currentWeapon].GetComponent <Animation>()["PistolSprinting"].normalizedTime = 0; weaponOrder[currentWeapon].GetComponent <Animation>()["PistolSprinting"].speed = 1.5f; weaponOrder[currentWeapon].GetComponent <Animation>().CrossFade("PistolSprinting", 0.00025f, PlayMode.StopAll); } else { //if player is sprinting, keep weapon in sprinting position during weapon switch weaponOrder[currentWeapon].GetComponent <Animation>()["PistolSprinting"].normalizedTime = 1; } } if (Time.timeSinceLevelLoad > 2) { if (CurrentWeaponBehaviorComponent.meleeSwingDelay == 0) { //move weapon down while switching IronsightsComponent.switchMove = -0.4f; } else { //move melee weapons down further while switching because they take more vertical screen space than guns IronsightsComponent.switchMove = -1.2f; } //wait for weapon down animation to play before switching weapons and animating weapon up yield return(new WaitForSeconds(0.2f)); } //immediately switch weapons (activate called weaponOrder index and deactivate all others) for (int i = 0; i < weaponOrder.Length; i++) { if (i == index) { #if UNITY_3_5 // Activate the selected weapon weaponOrder[i].SetActiveRecursively(true); #else // Activate the selected weapon weaponOrder[i].SetActive(true); #endif //get current weapon value from index currentWeapon = index; //synchronize current and previous weapon's y pos for correct offscreen switching, use localPosition not position for correct transforms weaponOrder[i].transform.localPosition = weaponOrder[i].transform.localPosition + new Vector3(0, weaponOrder[i].transform.localPosition.y - 0.3f, 0); if (Time.timeSinceLevelLoad > 2) { //move weapon up when switch finishes IronsightsComponent.switchMove = 0; } //if weapon uses rifle sprinting animation set speed and animate if (!weaponOrder[i].GetComponent <WeaponBehavior>().PistolSprintAnim) { //animate selected weapon up by setting time of animation to it's end and playing in reverse if (!FPSWalkerComponent.canRun) { weaponOrder[i].GetComponent <Animation>()["RifleSprinting"].normalizedTime = 1.0f; weaponOrder[i].GetComponent <Animation>()["RifleSprinting"].speed = -1.5f; weaponOrder[i].GetComponent <Animation>().CrossFade("RifleSprinting", 0.00025f, PlayMode.StopAll); } else { //if player is sprinting, keep weapon in sprinting position during weapon switch weaponOrder[i].GetComponent <Animation>()["RifleSprinting"].normalizedTime = 1.0f; weaponOrder[i].GetComponent <Animation>()["RifleSprinting"].speed = 1.5f; weaponOrder[i].GetComponent <Animation>().CrossFade("RifleSprinting", 0.00025f, PlayMode.StopAll); } } else //weapon uses pistol sprinting animation //animate selected weapon up by setting time of animation to it's end and playing in reverse { if (!FPSWalkerComponent.canRun) { weaponOrder[i].GetComponent <Animation>()["PistolSprinting"].normalizedTime = 1.0f; weaponOrder[i].GetComponent <Animation>()["PistolSprinting"].speed = -1.5f; weaponOrder[i].GetComponent <Animation>().CrossFade("PistolSprinting", 0.00025f, PlayMode.StopAll); } else { //if player is sprinting, keep weapon in sprinting position during weapon switch weaponOrder[i].GetComponent <Animation>()["PistolSprinting"].normalizedTime = 1.0f; weaponOrder[i].GetComponent <Animation>()["PistolSprinting"].speed = 1.5f; weaponOrder[i].GetComponent <Animation>().CrossFade("PistolSprinting", 0.00025f, PlayMode.StopAll); } } //update transform reference of active weapon object in other scipts IronsightsComponent.gun = weaponOrder[i].transform; //update active weapon object reference in other scipts IronsightsComponent.gunObj = weaponOrder[i]; CameraKickComponent.gun = weaponOrder[i]; } else { //reset transform of deactivated gun to make it in neutral position when selected again //use weapon parent transform.position instead of Camera.main.transform.position //or Camera.main.transform.localPosition to avoid positioning bugs due to camera pos changing with walking bob and kick weaponOrder[i].transform.position = myTransform.position; if (!weaponOrder[i].GetComponent <WeaponBehavior>().PistolSprintAnim) //weapon uses rifle sprinting animation //reset animation { weaponOrder[i].GetComponent <Animation>()["RifleSprinting"].normalizedTime = 1.0f; } else //weapon uses pistol sprinting animation //reset animation { weaponOrder[i].GetComponent <Animation>()["PistolSprinting"].normalizedTime = 1.0f; } //synchronize sprintState var in WeaponBehavior script weaponOrder[i].GetComponent <WeaponBehavior>().sprintState = true; #if UNITY_3_5 // Activate the selected weapon weaponOrder[i].SetActiveRecursively(false); #else // Activate the selected weapon weaponOrder[i].SetActive(false); #endif } } }
void FixedUpdate() { //set up external script references Ironsights IronsightsComponent = GetComponent <Ironsights>(); FPSRigidBodyWalker FPSWalkerComponent = GetComponent <FPSRigidBodyWalker>(); PlayerWeapons PlayerWeaponsComponent = weaponObj.GetComponent <PlayerWeapons>(); WeaponBehavior WeaponBehaviorComponent = PlayerWeaponsComponent.weaponOrder[PlayerWeaponsComponent.currentWeapon].GetComponent <WeaponBehavior>(); //Exit application if escape is pressed if (Input.GetKey(exitGame)) { if (Application.isEditor || Application.isWebPlayer) { //Application.Quit();//not used } else { //use this quit method because Application.Quit(); can cause crashes on exit in Unity 4 //if this issue is resolved in a newer Unity version, use Application.Quit here instead System.Diagnostics.Process.GetCurrentProcess().Kill(); } } //Restart level if v is pressed if (Input.GetKey(restartScene)) { Time.timeScale = 1.0f; //set timescale to 1.0f so fadeout wont take longer if bullet time is active GameObject llf = Instantiate(levelLoadFadeObj) as GameObject; //Create instance of levelLoadFadeObj //call FadeAndLoadLevel function with fadein argument set to false //in levelLoadFadeObj to restart level and fade screen out from black on level load llf.GetComponent <LevelLoadFade>().FadeAndLoadLevel(Color.black, 2.0f, false); //set restarting var to true to be accessed by FPSRigidBodyWalker script to stop rigidbody movement restarting = true; // Disable all scripts to deactivate player control upon player death foreach (var c in children) { Component[] coms = c.GetComponentsInChildren <MonoBehaviour>(); foreach (var b in coms) { MonoBehaviour p = b as MonoBehaviour; if (p) { p.enabled = false; } } } } //toggle or hold zooming state by determining if zoom button is pressed or held if (Input.GetKey(zoom) && WeaponBehaviorComponent.canZoom && !(FPSWalkerComponent.climbing && FPSWalkerComponent.lowerGunForClimb)) { if (!zoomStartState) { zoomStart = Time.time; //track time that zoom button was pressed zoomStartState = true; //perform these actions only once zoomEndState = false; if (zoomEnd - zoomStart < zoomDelay * Time.timeScale) //if button is tapped, toggle zoom state { if (!zoomed) { zoomed = true; } else { zoomed = false; } } } } else { if (!zoomEndState) { zoomEnd = Time.time; //track time that zoom button was released zoomEndState = true; zoomStartState = false; if (zoomEnd - zoomStart > zoomDelay * Time.timeScale) //if releasing zoom button after holding it down, stop zooming { zoomed = false; } } } //track when player stopped zooming to allow for delay of reticle becoming visible again if (zoomed) { zoomBtnState = false; //only perform this action once per button press } else { if (!zoomBtnState) { zoomStopTime = Time.time; zoomBtnState = true; } } //enable and disable crosshair based on various states like reloading and zooming if (IronsightsComponent.reloading || zoomed) { //don't disable reticle if player is using a melee weapon or if player is unarmed if (WeaponBehaviorComponent.meleeSwingDelay == 0 && !WeaponBehaviorComponent.unarmed) { if (crosshairVisibleState) { //disable the GUITexture element of the instantiated crosshair object //and set state so this action will only happen once. CrosshairGuiObjInstance.GetComponent <GUITexture>().enabled = false; crosshairVisibleState = false; } } } else { //Because of the method that is used for non magazine reloads, an additional check is needed here //to make the reticle appear after the last bullet reload time has elapsed. Proceed with no check //for magazine reloads. if ((WeaponBehaviorComponent.bulletsPerClip != WeaponBehaviorComponent.bulletsToReload && WeaponBehaviorComponent.reloadLastStartTime + WeaponBehaviorComponent.reloadLastTime < Time.time) || WeaponBehaviorComponent.bulletsPerClip == WeaponBehaviorComponent.bulletsToReload) { //allow a delay before enabling crosshair again to let the gun return to neutral position //by checking the zoomStopTime value if (!crosshairVisibleState && (zoomStopTime + 0.2f < Time.time)) { CrosshairGuiObjInstance.GetComponent <GUITexture>().enabled = true; crosshairVisibleState = true; } } } if (WeaponBehaviorComponent.showAimingCrosshair) { reticleColor.a = 0.25f; CrosshairGuiObjInstance.GetComponent <GUITexture>().color = reticleColor; } else { //make alpha of aiming reticle zero/transparent reticleColor.a = 0.0f; //set alpha of aiming reticle at start to prevent it from showing, but allow item pickup hand reticle CrosshairGuiObjInstance.GetComponent <GUITexture>().color = reticleColor; } //Pick up items RaycastHit hit; if (!IronsightsComponent.reloading && //no item pickup when reloading !WeaponBehaviorComponent.lastReload && //no item pickup when when reloading last round in non magazine reload !PlayerWeaponsComponent.switching && //no item pickup when switching weapons (!FPSWalkerComponent.canRun || FPSWalkerComponent.inputY == 0) //no item pickup when sprinting //there is a small delay between the end of canRun and the start of sprintSwitching (in PlayerWeapons script), //so track actual time that sprinting stopped to avoid the small time gap where the pickup hand shows briefly && ((FPSWalkerComponent.sprintStopTime + 0.4f) < Time.time)) { //raycast a line from the main camera's origin using a point extended forward from camera position/origin as a target to get the direction of the raycast //and scale the distance of the raycast based on the playerHeightMod value in the FPSRigidbodyWalker script if (Physics.Raycast(mainCamTransform.position, ((mainCamTransform.position + mainCamTransform.forward * (5.0f + (FPSWalkerComponent.playerHeightMod * 0.25f))) - mainCamTransform.position).normalized, out hit, 2.0f + FPSWalkerComponent.playerHeightMod, rayMask)) { if (hit.collider.gameObject.tag == "Usable") //if the object hit by the raycast is a pickup item and has the "Usable" tag { if (pickUpBtnState && Input.GetKey(use)) { //run the PickUpItem function in the pickup object's script hit.collider.SendMessageUpwards("PickUpItem", SendMessageOptions.DontRequireReceiver); //run the ActivateObject function of this object's script if it has the "Usable" tag hit.collider.SendMessageUpwards("ActivateObject", SendMessageOptions.DontRequireReceiver); pickUpBtnState = false; FPSWalkerComponent.cancelSprint = true; } //determine if pickup item is using a custom pickup reticle and if so set pickupTex to custom reticle if (pickUpBtnState) //check pickUpBtnState to prevent reticle from briefly showing custom/general pickup icon briefly when picking up last weapon before maxWeapons are obtained //determine if item under reticle is a weapon pickup { if (hit.collider.gameObject.GetComponent <WeaponPickup>()) { //set up external script references WeaponBehavior PickupWeaponBehaviorComponent = PlayerWeaponsComponent.weaponOrder[hit.collider.gameObject.GetComponent <WeaponPickup>().weaponNumber].GetComponent <WeaponBehavior>(); WeaponPickup WeaponPickupComponent = hit.collider.gameObject.GetComponent <WeaponPickup>(); if (PlayerWeaponsComponent.totalWeapons == PlayerWeaponsComponent.maxWeapons && //player has maximum weapons PickupWeaponBehaviorComponent.addsToTotalWeaps) //weapon adds to total inventory //player does not have weapon under reticle { if (!PickupWeaponBehaviorComponent.haveWeapon //and weapon under reticle hasn't been picked up from an item with removeOnUse set to false && !PickupWeaponBehaviorComponent.dropWillDupe) { if (!useSwapReticle) //if useSwapReticle is true, display swap reticle when item under reticle will replace current weapon { if (WeaponPickupComponent.weaponPickupReticle) { //display custom weapon pickup reticle if the weapon item has one defined pickupTex = WeaponPickupComponent.weaponPickupReticle; } else { //weapon has no custom pickup reticle, just show general pickup reticle pickupTex = pickupReticle; } } else { //display weapon swap reticle if player has max weapons and can swap held weapon for pickup under reticle pickupTex = swapReticle; } } else { //weapon under reticle is not removed on use and is in player's inventory, so show cantPickup reticle if (!WeaponPickupComponent.removeOnUse) { pickupTex = noPickupReticle; } else //weapon is removed on use, so show standard or custom pickup reticle { if (WeaponPickupComponent.weaponPickupReticle) { //display custom weapon pickup reticle if the weapon item has one defined pickupTex = WeaponPickupComponent.weaponPickupReticle; } else { //weapon has no custom pickup reticle, just show general pickup reticle pickupTex = pickupReticle; } } } } else //total weapons not at maximum and weapon under reticle does not add to inventory { if (!PickupWeaponBehaviorComponent.haveWeapon && !PickupWeaponBehaviorComponent.dropWillDupe || WeaponPickupComponent.removeOnUse) { if (WeaponPickupComponent.weaponPickupReticle) { //display custom weapon pickup reticle if the weapon item has one defined pickupTex = WeaponPickupComponent.weaponPickupReticle; } else { //weapon has no custom pickup reticle, just show general pickup reticle pickupTex = pickupReticle; } } else { pickupTex = noPickupReticle; } } //determine if item under reticle is a health pickup } else if (hit.collider.gameObject.GetComponent <HealthPickup>()) { //set up external script references HealthPickup HealthPickupComponent = hit.collider.gameObject.GetComponent <HealthPickup>(); if (HealthPickupComponent.healthPickupReticle) { pickupTex = HealthPickupComponent.healthPickupReticle; } else { pickupTex = pickupReticle; } //determine if item under reticle is an ammo pickup } else if (hit.collider.gameObject.GetComponent <AmmoPickup>()) { //set up external script references AmmoPickup AmmoPickupComponent = hit.collider.gameObject.GetComponent <AmmoPickup>(); if (AmmoPickupComponent.ammoPickupReticle) { pickupTex = AmmoPickupComponent.ammoPickupReticle; } else { pickupTex = pickupReticle; } } else { pickupTex = pickupReticle; } } UpdateReticle(false); //show pickupReticle if raycast hits a pickup item } else { if (crosshairTextureState) { UpdateReticle(true); //show aiming reticle crosshair if item is not a pickup item } } } else { if (crosshairTextureState) { UpdateReticle(true); //show aiming reticle crosshair if raycast hits nothing } } } else { if (crosshairTextureState) { UpdateReticle(true); //show aiming reticle crosshair if reloading, switching weapons, or sprinting } } //only register one press of E key to make player have to press button again to pickup items instead of holding E if (Input.GetKey(use)) { pickUpBtnState = false; } else { pickUpBtnState = true; } }
void Update() { //set up external script references Ironsights IronsightsComponent = GetComponent <Ironsights>(); AudioSource [] aSources = GetComponents <AudioSource>(); //Initialize audio source AudioSource otherfx = aSources[0] as AudioSource; if (Input.GetKeyDown(pauseGame)) //Pause game when pause button is pressed { if (Time.timeScale > 0) { pausedTime = Time.timeScale; Time.timeScale = 0; } else { Time.timeScale = pausedTime; } } if (Input.GetKeyDown(enterBulletTime)) //set bulletTimeActive to true or false based on button input { if (!bulletTimeActive) { otherfx.clip = enterBulletTimeFx; otherfx.PlayOneShot(otherfx.clip, 1.0f); //play enter bullet time sound effect bulletTimeActive = true; } else { otherfx.clip = exitBulletTimeFx; otherfx.PlayOneShot(otherfx.clip, 1.0f); //play exit bullet time sound effect bulletTimeActive = false; } } otherfx.pitch = Time.timeScale; //sync pitch of bullet time sound effects with Time.timescale if (Time.timeScale > 0) //decrease or increase Time.timescale when bulletTimeActive is true { if (bulletTimeActive) { Time.timeScale = Mathf.MoveTowards(Time.timeScale, bulletTimeSpeed, Time.deltaTime * 3.0f); } else { if (1.0f - Mathf.Abs(Time.timeScale) > 0.05f) //make sure that timescale returns to exactly 1.0f { Time.timeScale = Mathf.MoveTowards(Time.timeScale, 1.0f, Time.deltaTime * 3.0f); } else { Time.timeScale = 1.0f; } } } //set zoom mode to toggle, hold, or both, based on inspector setting switch (IronsightsComponent.zoomMode) { case Ironsights.zoomType.both: zoomDelay = 0.4f; break; case Ironsights.zoomType.hold: zoomDelay = 0.0f; break; case Ironsights.zoomType.toggle: zoomDelay = 999.0f; break; } }
void Start() { datacomps = GameObject.FindGameObjectWithTag("DataBase").GetComponent <DataComps>(); pauseManager = datacomps.gameObject.GetComponent <PauseManager> (); myTransform = transform; //define transforms for efficiency mainCamTransform = Camera.main.transform; //set up external script references InputComponent = playerObj.GetComponent <InputControl>(); FPSWalkerComponent = playerObj.GetComponent <FPSRigidBodyWalker>(); FPSPlayerComponent = playerObj.GetComponent <FPSPlayer>(); IronsightsComponent = playerObj.GetComponent <Ironsights>(); CameraControlComponent = mainCamTransform.GetComponent <CameraControl>(); CurrentWeaponBehaviorComponent = weaponOrder[firstWeapon].GetComponent <WeaponBehavior>(); WeaponBehavior BackupWeaponBehaviorComponent = weaponOrder[backupWeapon].GetComponent <WeaponBehavior>(); weaponBehaviors = myTransform.GetComponentsInChildren <WeaponBehavior>(true); aSources = transform.GetComponents <AudioSource>(); aSource = playerObj.AddComponent <AudioSource>(); aSource.spatialBlend = 0.0f; aSource.playOnAwake = false; //Create instance of GUIText to display ammo amount on hud. This will be accessed and updated by WeaponBehavior script. ammoGuiObjInstance = Instantiate(FPSPlayerComponent.ammoGuiObj, Vector3.zero, myTransform.rotation) as GameObject; //set the weapon order number in the WeaponBehavior scripts for (int i = 0; i < weaponOrder.Length; i++) { weaponOrder[i].GetComponent <WeaponBehavior>().weaponNumber = i; } currentGrenade = 0; GrenadeWeaponBehaviorComponent = grenadeOrder[currentGrenade].GetComponent <WeaponBehavior>(); grenadeWeapon = GrenadeWeaponBehaviorComponent.weaponNumber; //Select first weapon, if firstWeapon is not in inventory, player will spawn unarmed. if (weaponOrder[firstWeapon].GetComponent <WeaponBehavior>().haveWeapon) { StartCoroutine(SelectWeapon(firstWeapon)); } else { StartCoroutine(SelectWeapon(0)); } //set droppable value for backup weapon to false here if it was set to true in inspector //to prevent multiple instances of backup weapon from being dropped and not selecting next weapon BackupWeaponBehaviorComponent.droppable = false; //set addsToTotalWeaps value for backup weapon to false here if it was set to true in inspector //to prevent picking up a backup weapon from swapping current weapon BackupWeaponBehaviorComponent.addsToTotalWeaps = false; UpdateTotalWeapons(); //automatically assign sunlight object for weapon shading if (!sunLightObj) { Light[] lightList = FindObjectsOfType(typeof(Light)) as Light[]; for (int i = 0; i < lightList.Length; i++) { if (lightList[i].type == LightType.Directional && lightList[i].gameObject.activeInHierarchy) { sunLightObj = lightList[i].transform; break; } } } }
void Update() { //set up external script references Ironsights IronsightsComponent = GetComponent <Ironsights>(); AudioSource [] aSources = GetComponents <AudioSource>(); //Initialize audio source AudioSource otherfx = aSources[0] as AudioSource; if (Input.GetKeyDown(pauseGame)) //Pause game when pause button is pressed { if (Time.timeScale > 0) { pausedTime = Time.timeScale; Time.timeScale = 0; } else { Time.timeScale = pausedTime; } } if (Input.GetKeyDown(enterBulletTime)) //set bulletTimeActive to true or false based on button input { if (!bulletTimeActive) { otherfx.clip = enterBulletTimeFx; otherfx.PlayOneShot(otherfx.clip, 1.0f); //play enter bullet time sound effect bulletTimeActive = true; } else { otherfx.clip = exitBulletTimeFx; otherfx.PlayOneShot(otherfx.clip, 1.0f); //play exit bullet time sound effect bulletTimeActive = false; } } otherfx.pitch = Time.timeScale; //sync pitch of bullet time sound effects with Time.timescale if (Time.timeScale > 0) //decrease or increase Time.timescale when bulletTimeActive is true { if (bulletTimeActive) { Time.timeScale = Mathf.MoveTowards(Time.timeScale, bulletTimeSpeed, Time.deltaTime * 3.0f); } else { if (1.0f - Mathf.Abs(Time.timeScale) > 0.05f) //make sure that timescale returns to exactly 1.0f { Time.timeScale = Mathf.MoveTowards(Time.timeScale, 1.0f, Time.deltaTime * 3.0f); } else { Time.timeScale = 1.0f; } } } //set zoom mode to toggle, hold, or both, based on inspector setting switch (IronsightsComponent.zoomMode) { case Ironsights.zoomType.both: zoomDelay = 0.4f; break; case Ironsights.zoomType.hold: zoomDelay = 0.0f; break; case Ironsights.zoomType.toggle: zoomDelay = 999.0f; break; } //regenerate player health if regenerateHealth var is true if (regenerateHealth) { if (hitPoints < maxRegenHealth && timeLastDamaged + healthRegenDelay < Time.time) { HealPlayer(healthRegenRate * Time.deltaTime); } } //apply player hunger if usePlayerHunger var is true if (usePlayerHunger) { //increase player hunger if (lastHungerTime + hungerInterval < Time.time) { UpdateHunger(1.0f); } //calculate and apply starvation damage to player if (hungerPoints == maxHungerPoints && lastStarveTime + starveInterval < Time.time && hitPoints > 0.0f) { //use a negative heal amount to prevent unneeded damage effects of ApplyDamage function HealPlayer(starveAmt); //fade screen red when taking starvation damage GameObject pf = Instantiate(painFadeObj) as GameObject; //Create Instance of painFadeObj pf.GetComponent <PainFade>().FadeIn(PainColor, 0.75f); //Call FadeIn function in painFadeObj to fade screen red when damage taken //Call Die function if player's hitpoints have been depleted if (hitPoints < 1.0f) { SendMessage("Die"); //use SendMessage() to allow other script components on this object to detect player death } //update starvation timers timeLastDamaged = Time.time; lastStarveTime = Time.time; } } //apply player thirst if usePlayerThirst var is true if (usePlayerThirst) { //increase player hunger if (lastThirstTime + thirstInterval < Time.time) { UpdateThirst(1.0f); } //calculate and apply starvation damage to player if (thirstPoints == maxThirstPoints && lastThirstDamTime + thirstDamInterval < Time.time && hitPoints > 0.0f) { //use a negative heal amount to prevent unneeded damage effects of ApplyDamage function HealPlayer(thirstDamAmt); //fade screen red when taking starvation damage GameObject pf = Instantiate(painFadeObj) as GameObject; //Create Instance of painFadeObj pf.GetComponent <PainFade>().FadeIn(PainColor, 0.75f); //Call FadeIn function in painFadeObj to fade screen red when damage taken //Call Die function if player's hitpoints have been depleted if (hitPoints < 1.0f) { Die(); } //update starvation timers timeLastDamaged = Time.time; lastThirstDamTime = Time.time; } } }
void Update() { if (Time.timeScale > 0 && Time.deltaTime > 0) //allow pausing by setting timescale to 0 //set up external script references { FPSRigidBodyWalker FPSWalkerComponent = playerObj.GetComponent <FPSRigidBodyWalker>(); Ironsights IronsightsComponent = playerObj.GetComponent <Ironsights>(); WeaponBehavior WeaponBehaviorComponent = IronsightsComponent.gunObj.GetComponent <WeaponBehavior>(); HorizontalBob HorizontalBob = playerObj.GetComponent <HorizontalBob>(); FPSPlayer FPSPlayerComponent = playerObj.GetComponent <FPSPlayer>(); if (FPSWalkerComponent.canRun) //sprinting //set sway amounts for sprinting { swingAmt = 0.02f * swayAmount * WeaponBehaviorComponent.swayAmountUnzoomed; swingSpeed = 0.000025f * swayAmount * WeaponBehaviorComponent.swayAmountUnzoomed; rollSpeed = 0.0f * rollSwayAmount * WeaponBehaviorComponent.swayAmountUnzoomed; //smoothly change bobbing amounts for sprinting if (gunBobYaw < 12.0f * sprintBobYawAmount) { gunBobYaw += 60.0f * Time.deltaTime; } if (gunBobRoll < 15.0f * sprintBobRollAmount) { gunBobRoll += 60.0f * Time.deltaTime; } } else //walking //smoothly change bobbing amounts for walking { if (gunBobYaw > -16.0f * walkBobYawAmount) { gunBobYaw -= 60.0f * Time.deltaTime; } if (gunBobRoll > 10.0f * walkBobRollAmount) { gunBobRoll -= 60.0f * Time.deltaTime; } //set sway amounts based on player state if (!FPSPlayerComponent.zoomed || IronsightsComponent.reloading || WeaponBehaviorComponent.meleeSwingDelay != 0) { swingAmt = 0.035f * swayAmount * WeaponBehaviorComponent.swayAmountUnzoomed; swingSpeed = 0.00015f * swayAmount * WeaponBehaviorComponent.swayAmountUnzoomed; rollSpeed = 0.025f * rollSwayAmount * WeaponBehaviorComponent.swayAmountUnzoomed; } else { swingAmt = 0.025f * swayAmount * WeaponBehaviorComponent.swayAmountZoomed; swingSpeed = 0.0001f * swayAmount * WeaponBehaviorComponent.swayAmountZoomed; rollSpeed = 0.075f * rollSwayAmount * WeaponBehaviorComponent.swayAmountZoomed; } } //use both these z axes for independent animation of camera X and Y position and bobbing of camera roll zAxis1 = Camera.main.transform.localEulerAngles.z; zAxis2 = cameraObj.transform.localEulerAngles.z; //Set target angles to main camera angles targetRotation.x = cameraObj.transform.localEulerAngles.x; targetRotation.y = cameraObj.transform.localEulerAngles.y; targetRotation.z = Mathf.MoveTowardsAngle(zAxis1, zAxis2, Time.deltaTime / 16); //sway gun //find angle delta and reduce to smaller value localSide = Mathf.DeltaAngle(targetRotation2.y, targetRotation.y) * -(swingSpeed / Time.deltaTime); //pass sway value to ironsights script where gun position is calculated IronsightsComponent.side = Mathf.Clamp(localSide, -swingAmt, swingAmt); //find angle delta and reduce to smaller value localRaise = Mathf.DeltaAngle(targetRotation2.x, targetRotation.x) * (swingSpeed / Time.deltaTime); //pass sway value to ironsights script where gun position is calculated IronsightsComponent.raise = Mathf.Clamp(localRaise, -swingAmt, swingAmt); //calculate roll swaying of weapon and smooth with lerpAngle to minimize snapping of gun during extreme rotations localRoll = Mathf.LerpAngle(localRoll, Mathf.DeltaAngle(targetRotationRoll, targetRotation.y) * -rollSpeed * 3.0f, Time.deltaTime * 5.0f); //dampen angles of gun with main camera angles for swaying effects targetRotation2.x = Mathf.SmoothDampAngle(targetRotation2.x, targetRotation.x, ref dampVelocity1, dampSpeed, Mathf.Infinity, Time.deltaTime); targetRotation2.y = Mathf.SmoothDampAngle(targetRotation2.y, targetRotation.y, ref dampVelocity2, dampSpeed, Mathf.Infinity, Time.deltaTime); targetRotationRoll = Mathf.SmoothDampAngle(targetRotationRoll, targetRotation.y, ref dampVelocity6, 0.075f, Mathf.Infinity, Time.deltaTime); //set gun angles //set temporary vector to smoothed angles of gun and add yaw and roll bobbing and roll swaying Vector3 tempEulerAngles = new Vector3( (targetRotation.x), (targetRotation.y + (HorizontalBob.dampOrg * gunBobYaw)), (targetRotation.z + localRoll + (HorizontalBob.dampOrg * -gunBobRoll)) ); //finally, set actual weapon angles to the temporary vector's angles myTransform.localEulerAngles = tempEulerAngles; } }