Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Not able to rotate FPS camera vertically using Joystick Prefab

Discussion in 'Scripting' started by HBK_, Jan 8, 2018.

  1. HBK_

    HBK_

    Joined:
    Dec 1, 2017
    Posts:
    87
    hi everyone...i'm having a problem using the joystick to look around....here's the joystick script which i made with the help of a youtuber and all the changes are commented with "DCURRY" comment....
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.EventSystems;
    3. using UnitySampleAssets.CrossPlatformInput;
    4.  
    5. public class Joystick : MonoBehaviour , IPointerUpHandler , IPointerDownHandler , IDragHandler {
    6.  
    7.     public int MovementRange = 100;
    8.  
    9.     public enum AxisOption
    10.     {                                                    // Options for which axes to use                                                  
    11.         Both,                                                                   // Use both
    12.         OnlyHorizontal,                                                         // Only horizontal
    13.         OnlyVertical                                                            // Only vertical
    14.     }
    15.  
    16.     public AxisOption axesToUse = AxisOption.Both;   // The options for the axes that the still will use
    17.     public string horizontalAxisName = "Horizontal";// The name given to the horizontal axis for the cross platform input
    18.     public string verticalAxisName = "Vertical";    // The name given to the vertical axis for the cross platform input
    19.  
    20.     private Vector3 startPos;
    21.     private bool useX;                                                          // Toggle for using the x axis
    22.     private bool useY;                                                          // Toggle for using the Y axis
    23.     private CrossPlatformInputManager.VirtualAxis horizontalVirtualAxis;               // Reference to the joystick in the cross platform input
    24.     private CrossPlatformInputManager.VirtualAxis verticalVirtualAxis;                 // Reference to the joystick in the cross platform input
    25.    
    26. void Start () {//DCURRY changed this to Start from OnEnable
    27.         startPos = transform.position;
    28.         CreateVirtualAxes ();
    29.     }
    30.  
    31.     private void UpdateVirtualAxes (Vector3 value) {
    32.  
    33.         var delta = startPos - value;
    34.         delta.y = -delta.y;
    35.         delta /= MovementRange;
    36.         if(useX)
    37.         horizontalVirtualAxis.Update (-delta.x);
    38.  
    39.         if(useY)
    40.         verticalVirtualAxis.Update (delta.y);
    41.  
    42.     }
    43.  
    44.     private void CreateVirtualAxes()
    45.     {
    46.         // set axes to use
    47.         useX = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyHorizontal);
    48.         useY = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyVertical);
    49.  
    50.         // create new axes based on axes to use
    51.         if (useX)
    52.             horizontalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(horizontalAxisName);
    53.         if (useY)
    54.             verticalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(verticalAxisName);
    55.     }
    56.  
    57.  
    58.     public  void OnDrag(PointerEventData data) {
    59.         Vector3 newPos = Vector3.zero;
    60.         if (useX) {
    61.             int delta = (int) (data.position.x - startPos.x);//DCURRY deleted clamp
    62.             newPos.x = delta;
    63.         }
    64.         if (useY)
    65.         {
    66.    int delta = (int)(data.position.y - startPos.y);//DCURRY deleted clamp
    67.             newPos.y = delta;
    68.         }
    69.   //DCURRY added ClampMagnitude
    70.   transform.position = Vector3.ClampMagnitude( new Vector3(newPos.x , newPos.y , newPos.z), MovementRange) + startPos;
    71.         UpdateVirtualAxes (transform.position);
    72.     }
    73.  
    74.  
    75.     public  void OnPointerUp(PointerEventData data)
    76.     {
    77.         transform.position = startPos;
    78.         UpdateVirtualAxes (startPos);
    79.     }
    80.  
    81.  
    82.     public  void OnPointerDown (PointerEventData data) {
    83.     }
    84.  
    85.     void OnDisable () {
    86.         // remove the joysticks from the cross platform input
    87.         if (useX)
    88.         {
    89.             horizontalVirtualAxis.Remove();
    90.         }
    91.         if (useY)
    92.         {
    93.             verticalVirtualAxis.Remove();
    94.         }
    95.     }
    96. }
    97.  
    and here's the modified FirstPersonShooter Script and again the changes are commented with "DCURRY" comment..
    Code (CSharp):
    1. using UnityEngine;
    2. using UnitySampleAssets.CrossPlatformInput;
    3. using UnitySampleAssets.Utility;
    4.  
    5. namespace UnitySampleAssets.Characters.FirstPerson
    6. {
    7.     [RequireComponent(typeof (CharacterController))]
    8.     [RequireComponent(typeof (AudioSource))]
    9.     public class FirstPersonController : MonoBehaviour
    10.     {
    11.  
    12.         //////////////////////// exposed privates ///////////////////////
    13.         [SerializeField] private bool _isWalking;
    14.         [SerializeField] private float walkSpeed;
    15.         [SerializeField] private float runSpeed;
    16.         [SerializeField] private float lookSpeed = 4;
    17.         [SerializeField] [Range(0f, 1f)] private float runstepLenghten;
    18.         [SerializeField] private float jumpSpeed;
    19.         [SerializeField] private float stickToGroundForce;
    20.         [SerializeField] private float _gravityMultiplier;
    21.         [SerializeField] private MouseLook _mouseLook;
    22.         [SerializeField] private bool useFOVKick;
    23.         [SerializeField] private FOVKick _fovKick = new FOVKick();
    24.         [SerializeField] private bool useHeadBob;
    25.         [SerializeField] private CurveControlledBob _headBob = new CurveControlledBob();
    26.         [SerializeField] private LerpControlledBob _jumpBob = new LerpControlledBob();
    27.         [SerializeField] private float _stepInterval;
    28.  
    29.         [SerializeField] private AudioClip[] _footstepSounds;
    30.                                              // an array of footstep sounds that will be randomly selected from.
    31.  
    32.         [SerializeField] private AudioClip _jumpSound; // the sound played when character leaves the ground.
    33.         [SerializeField] private AudioClip _landSound; // the sound played when character touches back on ground.
    34.  
    35.         ///////////////// non exposed privates /////////////////////////
    36.         private Camera _camera;
    37.         private bool _jump;
    38.         private float _yRotation;
    39.         private CameraRefocus _cameraRefocus;
    40.         private Vector2 _input;
    41.         private Vector3 _moveDir = Vector3.zero;
    42.         private CharacterController _characterController;
    43.         private CollisionFlags _collisionFlags;
    44.         private bool _previouslyGrounded;
    45.         private Vector3 _originalCameraPosition;
    46.         private float _stepCycle = 0f;
    47.         private float _nextStep = 0f;
    48.         private bool _jumping = false;
    49.  
    50.         // Use this for initialization
    51.         private void Start()
    52.         {
    53.             _characterController = GetComponent<CharacterController>();
    54.             _camera = Camera.main;
    55.             _originalCameraPosition = _camera.transform.localPosition;
    56.             _cameraRefocus = new CameraRefocus(_camera, transform, _camera.transform.localPosition);
    57.             _fovKick.Setup(_camera);
    58.             _headBob.Setup(_camera, _stepInterval);
    59.             _stepCycle = 0f;
    60.             _nextStep = _stepCycle/2f;
    61.             _jumping = false;
    62.         }
    63.  
    64.         // Update is called once per frame
    65.         private void Update()
    66.         {
    67.            
    68.                      float speed = 3.0f;
    69.          float xRot = speed * Input.GetAxis("VerticalLook");
    70.          float yRot = speed * Input.GetAxis("HorizontalLook");
    71.        
    72.          transform.Rotate(xRot, yRot, 0.0f);
    73.        
    74.             RotateView();
    75.             // the jump state needs to read here to make sure it is not missed
    76.             if (!_jump)
    77.                 _jump = CrossPlatformInputManager.GetButtonDown("Jump");
    78.  
    79.             if (!_previouslyGrounded && _characterController.isGrounded)
    80.             {
    81.                 StartCoroutine(_jumpBob.DoBobCycle());
    82.                 PlayLandingSound();
    83.                 _moveDir.y = 0f;
    84.                 _jumping = false;
    85.             }
    86.             if (!_characterController.isGrounded && !_jumping && _previouslyGrounded)
    87.             {
    88.                 _moveDir.y = 0f;
    89.             }
    90.  
    91.             _previouslyGrounded = _characterController.isGrounded;
    92.         }
    93.  
    94.         private void PlayLandingSound()
    95.         {
    96.             GetComponent<AudioSource>().clip = _landSound;
    97.             GetComponent<AudioSource>().Play();
    98.             _nextStep = _stepCycle + .5f;
    99.         }
    100.  
    101.         private void FixedUpdate()
    102.         {
    103.             float speed;
    104.             GetInput(out speed);
    105.             // always move along the camera forward as it is the direction that it being aimed at
    106.             Vector3 desiredMove = _camera.transform.forward*_input.y + _camera.transform.right*_input.x;
    107.  
    108.             // get a normal for the surface that is being touched to move along it
    109.             RaycastHit hitInfo;
    110.             Physics.SphereCast(transform.position, _characterController.radius, Vector3.down, out hitInfo,
    111.                                _characterController.height/2f);
    112.             desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
    113.  
    114.             _moveDir.x = desiredMove.x*speed;
    115.             _moveDir.z = desiredMove.z*speed;
    116.  
    117.  
    118.             if (_characterController.isGrounded)
    119.             {
    120.                 _moveDir.y = -stickToGroundForce;
    121.  
    122.                 if (_jump)
    123.                 {
    124.                     _moveDir.y = jumpSpeed;
    125.                     PlayJumpSound();
    126.                     _jump = false;
    127.                     _jumping = true;
    128.                 }
    129.             }
    130.             else
    131.             {
    132.                 _moveDir += Physics.gravity*_gravityMultiplier;
    133.             }
    134.  
    135.             _collisionFlags = _characterController.Move(_moveDir*Time.fixedDeltaTime);
    136.  
    137.             ProgressStepCycle(speed);
    138.             UpdateCameraPosition(speed);
    139.         }
    140.  
    141.         private void PlayJumpSound()
    142.         {
    143.             GetComponent<AudioSource>().clip = _jumpSound;
    144.             GetComponent<AudioSource>().Play();
    145.         }
    146.  
    147.         private void ProgressStepCycle(float speed)
    148.         {
    149.             if (_characterController.velocity.sqrMagnitude > 0 && (_input.x != 0 || _input.y != 0))
    150.                 _stepCycle += (_characterController.velocity.magnitude + (speed*(_isWalking ? 1f : runstepLenghten)))*
    151.                               Time.fixedDeltaTime;
    152.  
    153.             if (!(_stepCycle > _nextStep)) return;
    154.  
    155.             _nextStep = _stepCycle + _stepInterval;
    156.  
    157.             PlayFootStepAudio();
    158.         }
    159.  
    160.         private void PlayFootStepAudio()
    161.         {
    162.             if (!_characterController.isGrounded) return;
    163.             // pick & play a random footstep sound from the array,
    164.             // excluding sound at index 0
    165.             int n = Random.Range(1, _footstepSounds.Length);
    166.             GetComponent<AudioSource>().clip = _footstepSounds[n];
    167.             GetComponent<AudioSource>().PlayOneShot(GetComponent<AudioSource>().clip);
    168.             // move picked sound to index 0 so it's not picked next time
    169.             _footstepSounds[n] = _footstepSounds[0];
    170.             _footstepSounds[0] = GetComponent<AudioSource>().clip;
    171.         }
    172.  
    173.         private void UpdateCameraPosition(float speed)
    174.         {
    175.             Vector3 newCameraPosition;
    176.             if (!useHeadBob) return;
    177.             if (_characterController.velocity.magnitude > 0 && _characterController.isGrounded)
    178.             {
    179.                 _camera.transform.localPosition =
    180.                     _headBob.DoHeadBob(_characterController.velocity.magnitude +
    181.                                        (speed*(_isWalking ? 1f : runstepLenghten)));
    182.                 newCameraPosition = _camera.transform.localPosition;
    183.                 newCameraPosition.y = _camera.transform.localPosition.y - _jumpBob.Offset();
    184.             }
    185.             else
    186.             {
    187.                 newCameraPosition = _camera.transform.localPosition;
    188.                 newCameraPosition.y = _originalCameraPosition.y - _jumpBob.Offset();
    189.             }
    190.             _camera.transform.localPosition = newCameraPosition;
    191.  
    192.             _cameraRefocus.SetFocusPoint();
    193.         }
    194.  
    195.         private void GetInput(out float speed)
    196.         {
    197.             // Read input
    198.             float horizontal = CrossPlatformInputManager.GetAxisRaw("Horizontal");
    199.             float vertical = CrossPlatformInputManager.GetAxisRaw("Vertical");
    200.  
    201.             bool waswalking = _isWalking;
    202.  
    203. #if !MOBILE_INPUT
    204.             // On standalone builds, walk/run speed is modified by a key press.
    205.             // keep track of whether or not the character is walking or running
    206.             _isWalking = !Input.GetKey(KeyCode.LeftShift);
    207. #endif
    208.             // set the desired speed to be walking or running
    209.             speed = _isWalking ? walkSpeed : runSpeed;
    210.             _input = new Vector2(horizontal, vertical);
    211.  
    212.             // normalize input if it exceeds 1 in combined length:
    213.             if (_input.sqrMagnitude > 1) _input.Normalize();
    214.  
    215.             // handle speed change to give an fov kick
    216.             // only if the player is going to a run, is running and the fovkick is to be used
    217.             if (_isWalking != waswalking && useFOVKick && _characterController.velocity.sqrMagnitude > 0)
    218.             {
    219.                 StopAllCoroutines();
    220.                 StartCoroutine(!_isWalking ? _fovKick.FOVKickUp() : _fovKick.FOVKickDown());
    221.             }
    222.         }
    223.  
    224.         private void RotateView()
    225.         {    //DCURRY added else for mobile input
    226.    #if !MOBILE_INPUT
    227.             Vector2 mouseInput = _mouseLook.Clamped(_yRotation, transform.localEulerAngles.y);
    228.          Debug.Log ("Starting Connection!");
    229.    _camera.transform.localEulerAngles = new Vector3(-mouseInput.y, _camera.transform.localEulerAngles.y,
    230.                                                     _camera.transform.localEulerAngles.z);
    231.    transform.localEulerAngles = new Vector3(0, mouseInput.x, 0);
    232.    #else
    233.    Vector2 mouseInput = new Vector2(CrossPlatformInputManager.GetAxisRaw("HorizontalLook"),
    234.                                     CrossPlatformInputManager.GetAxisRaw("VerticalLook"));
    235.    float camX = _camera.transform.localEulerAngles.y;
    236.    if((camX > 280 && camX <= 360) ||
    237.       (camX >= 0 && camX < 80) ||
    238.       (camX >= 80 && camX < 180 && mouseInput.y > 0) ||
    239.       (camX > 180 && camX <= 280 && mouseInput.y < 0))
    240.    {
    241.     _camera.transform.localEulerAngles += new Vector3(-mouseInput.y * lookSpeed * .7f, _camera.transform.localEulerAngles.y,
    242.                                                       _camera.transform.localEulerAngles.z);
    243.    }
    244.    transform.localEulerAngles += new Vector3(0, mouseInput.x * lookSpeed, 0);
    245.    #endif
    246.  
    247.             // handle the roation round the x axis on the camera
    248.             _yRotation = mouseInput.y;
    249.             _cameraRefocus.GetFocusPoint();
    250.         }
    251.  
    252.         private void OnControllerColliderHit(ControllerColliderHit hit)
    253.         {
    254.             Rigidbody body = hit.collider.attachedRigidbody;
    255.             if (body == null || body.isKinematic)
    256.                 return;
    257.  
    258.             //dont move the rigidbody if the character is on top of it
    259.             if (_collisionFlags == CollisionFlags.CollidedBelow) return;
    260.  
    261.             body.AddForceAtPosition(_characterController.velocity*0.1f, hit.point, ForceMode.Impulse);
    262.  
    263.         }
    264.     }
    265. }
    the problem is i am able to use HorizontalLook and able to rotate my player's view using right joystick made for looking around but i'm not able to look Vertically using it...i used same code and same settings in my previous project which was same and it was working and i was able to look upside down but in this project i'm only able to use Horizontal axis....Any Help Will be appreciated!!...