Ok so i’ve been making a first person game and cannot figure out how to lock and unlock the cursor. I am using the default fps character controller from the standard assets which has a script built in that allows you to unlock the cursor by pressing escape and to re lock the cursor by clicking on the screen again and i am able to change that to some other key and have it work but i cannot in anyway make the method that triggers the cursor locking and unlocking take any sort of input from any other script or from another method within the same script. The closest I gotten is i got another script to activate a method i put into the mouselook script called LockCursor and UnlockCursor which changes a bool variable deathTrigger and then triggers an update in the method that checks to see if if the cursor should be locked or not and in that method i added an if statement the method that checks the deathTrigger and if it is true then change the variable that tells the later part of the method to unlock the cursor and ive gotton the methods that change the deathTrigger variable to activate from another script but then cursor wont unlock. ive also tried just copying the two commands that tell the cursor to lock and unlock ( Cursor.lockState = CursorLockMode.None; Cursor.visible = true; ) into another script and that doesn’t work either sooo what am i doing wrong?
Here are the scripts:
MouseLook
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
//namespace UnityStandardAssets.Characters.FirstPerson
//{
[Serializable]
public class MouseLook {
public float XSensitivity = 2f;
public float YSensitivity = 2f;
public bool clampVerticalRotation = true;
public float MinimumX = -90F;
public float MaximumX = 90F;
public bool smooth;
public float smoothTime = 5f;
public bool lockCursor = true;
private Quaternion m_CharacterTargetRot;
private Quaternion m_CameraTargetRot;
public bool m_cursorIsLocked = true;
public bool deathTrigger = false;
public void Init(Transform character, Transform camera)
{
m_CharacterTargetRot = character.localRotation;
m_CameraTargetRot = camera.localRotation;
}
public void LookRotation(Transform character, Transform camera)
{
float yRot = CrossPlatformInputManager.GetAxis("Mouse X") * XSensitivity;
float xRot = CrossPlatformInputManager.GetAxis("Mouse Y") * YSensitivity;
m_CharacterTargetRot *= Quaternion.Euler (0f, yRot, 0f);
m_CameraTargetRot *= Quaternion.Euler (-xRot, 0f, 0f);
if(clampVerticalRotation)
m_CameraTargetRot = ClampRotationAroundXAxis (m_CameraTargetRot);
if(smooth)
{
character.localRotation = Quaternion.Slerp (character.localRotation, m_CharacterTargetRot,
smoothTime * Time.deltaTime);
camera.localRotation = Quaternion.Slerp (camera.localRotation, m_CameraTargetRot,
smoothTime * Time.deltaTime);
}
else
{
character.localRotation = m_CharacterTargetRot;
camera.localRotation = m_CameraTargetRot;
}
UpdateCursorLock();
}
public void SetCursorLock(bool value)
{
lockCursor = value;
if(!lockCursor)
{//we force unlock the cursor if the user disable the cursor locking helper
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
}
public void UpdateCursorLock()
{
//if the user set "lockCursor" we check & properly lock the cursos
if (lockCursor)
InternalLockUpdate();
}
private void InternalLockUpdate()
{
if(deathTrigger == true)
{
m_cursorIsLocked = false;
}
else if(deathTrigger == false)
{
m_cursorIsLocked = true;
}
if(Input.GetKeyUp(KeyCode.Escape))
{
m_cursorIsLocked = false;
}
else if(Input.GetMouseButtonUp(0))
{
m_cursorIsLocked = true;
}
if (m_cursorIsLocked)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
else if (!m_cursorIsLocked)
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
}
Quaternion ClampRotationAroundXAxis(Quaternion q)
{
q.x /= q.w;
q.y /= q.w;
q.z /= q.w;
q.w = 1.0f;
float angleX = 2.0f * Mathf.Rad2Deg * Mathf.Atan (q.x);
angleX = Mathf.Clamp (angleX, MinimumX, MaximumX);
q.x = Mathf.Tan (0.5f * Mathf.Deg2Rad * angleX);
return q;
}
public void LockCursor(){
deathTrigger = true;
UpdateCursorLock();
}
public void UnLockCursor(){
deathTrigger = false;
UpdateCursorLock();
}
}
//}
Death
using UnityEngine;
using System.Collections;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
public class Death : MonoBehaviour {
private ShowPanels showPanels; //Reference to the ShowPanels script used to hide and show UI panels
private StartOptions startOptions;
private MouseLock m_MouseLock;
public bool isDead;
//Awake is called before Start()
void Awake()
{
//Get a component reference to ShowPanels attached to this object, store in showPanels variable
showPanels = GetComponent<ShowPanels> ();
startOptions = GetComponent<StartOptions>();
mouseLock = GetComponent<MouseLock>();
}
// Update is called once per frame
private void Update()
{
}
public void Dead()
{
//Set time.timescale to 0, this will cause animations and physics to stop updating
Time.timeScale = 0;
//call the ShowPausePanel function of the ShowPanels script
showPanels.HideCrossHair();
showPanels.ShowDeathPanel();
startOptions.InMenu();
isDead = true;
fPSController.UnLockCursor();
}
public void UnDead()
{
//Set time.timescale to 1, this will cause animations and physics to continue updating at regular speed
Time.timeScale = 1;
//call the HidePausePanel function of the ShowPanels script
showPanels.ShowCrossHair ();
showPanels.HideDeathPanel ();
startOptions.NotInMenu();
isDead = false;
mouseLook.LockCursor();
}
public void BackToMenu()
{
//Set time.timescale to 1, this will cause animations and physics to continue updating at regular speed
Time.timeScale = 1;
//call the HidePausePanel function of the ShowPanels script
showPanels.ShowCrossHair();
showPanels.HideDeathPanel();
startOptions.BackToMenu();
isDead = false;
mouseLook.UnLockCursor();
}
}
Any help you could give would be very much appreciated and just so you know i’m relatively new to unity but i have had a fair amount programming experience so if its something completely obvious i wouldn’t be surprised.
Thanks -Jared_Brian_
Update:
Ok i don’t know what i did but now i cant get the deathTrigger variable to change at all and i didnt change anything its possible that i was just crazy when i saw it change. i’m at a loss i have no idea what i’m doing wrong.
any help you can offer will be greatly appreciated
All i want it to do is have the cursor locked so you can use the FPS controller when not paused or in a menu and to be unlocked when you die (which does make a menu pop up) or when in a menu. and i just tested it and it dosent work when its built either and it did make the death screen pop up so it is activating.
here is what i changed the death script too:
Death
using UnityEngine;
using System.Collections;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
public class Death : MonoBehaviour {
private ShowPanels showPanels; //Reference to the ShowPanels script used to hide and show UI panels
private StartOptions startOptions;
[SerializeField] private MouseLook m_MouseLook;
//private FirstPersonController fPSController;
public bool isDead;
//Awake is called before Start()
void Awake()
{
//Get a component reference to ShowPanels attached to this object, store in showPanels variable
showPanels = GetComponent<ShowPanels> ();
startOptions = GetComponent<StartOptions>();
m_MouseLook = GetComponent<MouseLook>();
}
// Update is called once per frame
private void Update()
{
}
public void Dead()
{
//Set time.timescale to 0, this will cause animations and physics to stop updating
Time.timeScale = 0;
//call the ShowPausePanel function of the ShowPanels script
showPanels.HideCrossHair();
showPanels.ShowDeathPanel();
startOptions.InMenu();
isDead = true;
m_MouseLook.UnLockCursor();
}
public void UnDead()
{
//Set time.timescale to 1, this will cause animations and physics to continue updating at regular speed
Time.timeScale = 1;
//call the HidePausePanel function of the ShowPanels script
showPanels.ShowCrossHair ();
showPanels.HideDeathPanel ();
startOptions.NotInMenu();
isDead = false;
//m_MouseLook.LockCursor();
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
public void BackToMenu()
{
//Set time.timescale to 1, this will cause animations and physics to continue updating at regular speed
Time.timeScale = 1;
//call the HidePausePanel function of the ShowPanels script
showPanels.ShowCrossHair();
showPanels.HideDeathPanel();
startOptions.BackToMenu();
isDead = false;
//m_MouseLook.UnLockCursor();
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
Ok so i’m assuming this is supposed to go into the FirstPersonController script and after a little trial and error i got it into the script without any errors but it doesn’t appear to do anything when i press the backspace key which based on just reading the code is supposed to toggle the cursor lock.
Here is the script:
(i put the method in at the bottom as well as some variables i had to create in order for there to not be any errors)
FirstPersonController
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;
//namespace UnityStandardAssets.Characters.FirstPerson
//{
[RequireComponent(typeof (CharacterController))]
[RequireComponent(typeof (AudioSource))]
public class FirstPersonController : MonoBehaviour
{
[SerializeField] private bool m_IsWalking;
[SerializeField] private float m_WalkSpeed;
[SerializeField] private float m_RunSpeed;
[SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
[SerializeField] private float m_JumpSpeed;
[SerializeField] private float m_StickToGroundForce;
[SerializeField] private float m_GravityMultiplier;
[SerializeField] private MouseLook m_MouseLook;
[SerializeField] private bool m_UseFovKick;
[SerializeField] private FOVKick m_FovKick = new FOVKick();
[SerializeField] private bool m_UseHeadBob;
[SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
[SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
[SerializeField] private float m_StepInterval;
[SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from.
[SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground.
[SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground.
private Camera m_Camera;
private bool m_Jump;
private float m_YRotation;
private Vector2 m_Input;
private Vector3 m_MoveDir = Vector3.zero;
private CharacterController m_CharacterController;
private CollisionFlags m_CollisionFlags;
private bool m_PreviouslyGrounded;
private Vector3 m_OriginalCameraPosition;
private float m_StepCycle;
private float m_NextStep;
private bool m_Jumping;
private AudioSource m_AudioSource;
// Use this for initialization
private void Start()
{
m_CharacterController = GetComponent<CharacterController>();
m_Camera = Camera.main;
m_OriginalCameraPosition = m_Camera.transform.localPosition;
m_FovKick.Setup(m_Camera);
m_HeadBob.Setup(m_Camera, m_StepInterval);
m_StepCycle = 0f;
m_NextStep = m_StepCycle/2f;
m_Jumping = false;
m_AudioSource = GetComponent<AudioSource>();
m_MouseLook.Init(transform , m_Camera.transform);
}
// Update is called once per frame
private void Update()
{
RotateView();
// the jump state needs to read here to make sure it is not missed
if (!m_Jump)
{
m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}
if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
{
StartCoroutine(m_JumpBob.DoBobCycle());
PlayLandingSound();
m_MoveDir.y = 0f;
m_Jumping = false;
}
if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
{
m_MoveDir.y = 0f;
}
m_PreviouslyGrounded = m_CharacterController.isGrounded;
}
private void PlayLandingSound()
{
m_AudioSource.clip = m_LandSound;
m_AudioSource.Play();
m_NextStep = m_StepCycle + .5f;
}
private void FixedUpdate()
{
float speed;
GetInput(out speed);
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x;
// get a normal for the surface that is being touched to move along it
RaycastHit hitInfo;
Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
m_CharacterController.height/2f, ~0, QueryTriggerInteraction.Ignore);
desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
m_MoveDir.x = desiredMove.x*speed;
m_MoveDir.z = desiredMove.z*speed;
if (m_CharacterController.isGrounded)
{
m_MoveDir.y = -m_StickToGroundForce;
if (m_Jump)
{
m_MoveDir.y = m_JumpSpeed;
PlayJumpSound();
m_Jump = false;
m_Jumping = true;
}
}
else
{
m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime;
}
m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime);
ProgressStepCycle(speed);
UpdateCameraPosition(speed);
//GameObject go = GameObject.Find("UI");
//StartOptions SO = (StartOptions)go.GetComponent(typeof(StartOptions));
m_MouseLook.UpdateCursorLock();
}
private void PlayJumpSound()
{
m_AudioSource.clip = m_JumpSound;
m_AudioSource.Play();
}
private void ProgressStepCycle(float speed)
{
if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
{
m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
Time.fixedDeltaTime;
}
if (!(m_StepCycle > m_NextStep))
{
return;
}
m_NextStep = m_StepCycle + m_StepInterval;
PlayFootStepAudio();
}
private void PlayFootStepAudio()
{
if (!m_CharacterController.isGrounded)
{
return;
}
// pick & play a random footstep sound from the array,
// excluding sound at index 0
int n = Random.Range(1, m_FootstepSounds.Length);
m_AudioSource.clip = m_FootstepSounds[n];
m_AudioSource.PlayOneShot(m_AudioSource.clip);
// move picked sound to index 0 so it's not picked next time
m_FootstepSounds[n] = m_FootstepSounds[0];
m_FootstepSounds[0] = m_AudioSource.clip;
}
private void UpdateCameraPosition(float speed)
{
Vector3 newCameraPosition;
if (!m_UseHeadBob)
{
return;
}
if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
{
m_Camera.transform.localPosition =
m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
(speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
}
else
{
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
}
m_Camera.transform.localPosition = newCameraPosition;
}
private void GetInput(out float speed)
{
// Read input
float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
float vertical = CrossPlatformInputManager.GetAxis("Vertical");
bool waswalking = m_IsWalking;
#if !MOBILE_INPUT
// On standalone builds, walk/run speed is modified by a key press.
// keep track of whether or not the character is walking or running
m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
#endif
// set the desired speed to be walking or running
speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
m_Input = new Vector2(horizontal, vertical);
// normalize input if it exceeds 1 in combined length:
if (m_Input.sqrMagnitude > 1)
{
m_Input.Normalize();
}
// handle speed change to give an fov kick
// only if the player is going to a run, is running and the fovkick is to be used
if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
{
StopAllCoroutines();
StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
}
}
private void RotateView()
{
m_MouseLook.LookRotation (transform, m_Camera.transform);
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
//dont move the rigidbody if the character is on top of it
if (m_CollisionFlags == CollisionFlags.Below)
{
return;
}
if (body == null || body.isKinematic)
{
return;
}
body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
}
public void LockCursor()
{
m_MouseLook.m_cursorIsLocked = true;
m_MouseLook.UpdateCursorLock();
}
public void UnLockCursor()
{
m_MouseLook.m_cursorIsLocked = false;
m_MouseLook.UpdateCursorLock();
}
public float mouseVertical;
public float mouseHorizontal;
public Quaternion camRotation;
private void FirstPersonCursorCtrl()
{
if (Input.GetKeyDown(KeyCode.Backspace))
{
if (Cursor.lockState == CursorLockMode.None)
{
Cursor.lockState = CursorLockMode.Locked;
}
else
{
Cursor.lockState = CursorLockMode.None;
}
}
if (Cursor.lockState == CursorLockMode.Locked)
{
mouseVertical -= Input.GetAxis("Mouse Y") * Time.deltaTime * 100f;
mouseHorizontal += Input.GetAxis("Mouse X") * Time.deltaTime * 100f;
camRotation = Quaternion.Euler(mouseVertical, mouseHorizontal, 0f);
transform.rotation = camRotation;
}
}
}
//}
and then i also tried to just have it in the mouse look script but it said that it didn’t recognize “transform” in its current context so where are you supposed to put this method and how do you run it properly?
oh well that was a stupid mistake on my part but even after calling it from update it still didn’t do anything unfortunately.
did i accidentally take something important out when changing it so it doesn’t have errors?