Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Strange player movement with relation to mouse

Discussion in 'Scripting' started by BT723, Jul 5, 2018.

  1. BT723

    BT723

    Joined:
    Apr 11, 2018
    Posts:
    30
    For some strange reason whenever i move my mouse up the player moves forward and when i look down it moves backwards i believe it is one of the following scripts that is the problem but i'm not sure. this is not my code but is from an asset pack.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class FirstPersonCharacter : MonoBehaviour
    5. {
    6.     [SerializeField] private float runSpeed = 8f;                                       // The speed at which we want the character to move
    7.     [SerializeField] private float strafeSpeed = 4f;                                    // The speed at which we want the character to be able to strafe
    8.     [SerializeField] private float jumpPower = 5f;                                      // The power behind the characters jump. increase for higher jumps
    9.    
    10.     [SerializeField] private AdvancedSettings advanced = new AdvancedSettings();        // The container for the advanced settings ( done this way so that the advanced setting are exposed under a foldout
    11.     [SerializeField] private bool lockCursor = true;
    12.  
    13.     [System.Serializable]
    14.     public class AdvancedSettings                                                       // The advanced settings
    15.     {
    16.         public float gravityMultiplier = 1f;                                            // Changes the way gravity effect the player ( realistic gravity can look bad for jumping in game )
    17.         public PhysicMaterial zeroFrictionMaterial;                                     // Material used for zero friction simulation
    18.         public PhysicMaterial highFrictionMaterial;                                     // Material used for high friction ( can stop character sliding down slopes )
    19.         public float groundStickyEffect = 5f;                                            // power of 'stick to ground' effect - prevents bumping down slopes.
    20.     }
    21.    
    22.     private CapsuleCollider capsule;                                                    // The capsule collider for the first person character
    23.     private const float jumpRayLength = 0.7f;                                           // The length of the ray used for testing against the ground when jumping
    24.     public bool grounded { get; private set; }
    25.     private Vector2 input;
    26.     private IComparer rayHitComparer;
    27.    
    28.     void Awake ()
    29.     {
    30.         // Set up a reference to the capsule collider.
    31.         capsule = GetComponent<Collider>() as CapsuleCollider;
    32.         grounded = true;
    33.         rayHitComparer = new RayHitComparer();
    34.  
    35.         if (lockCursor)
    36.         {
    37.             Cursor.lockState = CursorLockMode.Locked;
    38.             Cursor.visible = false;
    39.         }
    40.         else
    41.         {
    42.             Cursor.lockState = CursorLockMode.None;
    43.             Cursor.visible = true;
    44.         }
    45.     }
    46.  
    47.     void OnDisable()
    48.     {
    49.         Cursor.lockState = CursorLockMode.None;
    50.         Cursor.visible = true;
    51.     }
    52.    
    53.     void Update()
    54.     {
    55.         if (Input.GetMouseButtonUp(0))
    56.         {
    57.             Cursor.lockState = CursorLockMode.Locked;
    58.             Cursor.visible = false;
    59.         }
    60.         if (Input.GetKeyDown(KeyCode.Escape))
    61.         {
    62.             Cursor.lockState = CursorLockMode.None;
    63.             Cursor.visible = true;
    64.         }
    65.     }
    66.    
    67.    
    68.     public void FixedUpdate ()
    69.     {
    70.         float speed = runSpeed;
    71.        
    72.         float h = Input.GetAxis("Horizontal");
    73.         float v = Input.GetAxis("Vertical");
    74.         bool jump = Input.GetButton("Jump");
    75.        
    76.         input = new Vector2( h, v );
    77.  
    78.         // normalize input if it exceeds 1 in combined length:
    79.         if (input.sqrMagnitude > 1) input.Normalize();
    80.        
    81.         // Get a vector which is desired move as a world-relative direction, including speeds
    82.         Vector3 desiredMove = transform.forward * input.y * speed + transform.right * input.x * strafeSpeed;
    83.        
    84.         // preserving current y velocity (for falling, gravity)
    85.         float yv = GetComponent<Rigidbody>().velocity.y;
    86.        
    87.         // add jump power
    88.         if (grounded && jump) {
    89.             yv += jumpPower;
    90.             grounded = false;
    91.         }
    92.        
    93.         // Set the rigidbody's velocity according to the ground angle and desired move
    94.         GetComponent<Rigidbody>().velocity = desiredMove + Vector3.up * yv;
    95.        
    96.         // Use low/high friction depending on whether we're moving or not
    97.         if (desiredMove.magnitude > 0 || !grounded)
    98.         {
    99.             GetComponent<Collider>().material = advanced.zeroFrictionMaterial;
    100.         } else {
    101.             GetComponent<Collider>().material = advanced.highFrictionMaterial;
    102.         }
    103.  
    104.        
    105.         // Ground Check:
    106.        
    107.         // Create a ray that points down from the centre of the character.
    108.         Ray ray = new Ray(transform.position, -transform.up);
    109.        
    110.         // Raycast slightly further than the capsule (as determined by jumpRayLength)
    111.         RaycastHit[] hits = Physics.RaycastAll(ray, capsule.height * jumpRayLength );
    112.         System.Array.Sort (hits, rayHitComparer);
    113.        
    114.        
    115.         if (grounded || GetComponent<Rigidbody>().velocity.y < jumpPower * .5f)
    116.         {
    117.             // Default value if nothing is detected:
    118.             grounded = false;
    119.             // Check every collider hit by the ray
    120.             for (int i = 0; i < hits.Length; i++)
    121.             {
    122.                 // Check it's not a trigger
    123.                 if (!hits[i].collider.isTrigger)
    124.                 {
    125.                     // The character is grounded, and we store the ground angle (calculated from the normal)
    126.                     grounded = true;
    127.                    
    128.                     // stick to surface - helps character stick to ground - specially when running down slopes
    129.                     //if (rigidbody.velocity.y <= 0) {
    130.                     GetComponent<Rigidbody>().position = Vector3.MoveTowards (GetComponent<Rigidbody>().position, hits[i].point + Vector3.up * capsule.height*.5f, Time.deltaTime * advanced.groundStickyEffect);
    131.                     //}
    132.                     GetComponent<Rigidbody>().velocity = new Vector3(GetComponent<Rigidbody>().velocity.x, 0, GetComponent<Rigidbody>().velocity.z);
    133.                     break;
    134.                 }
    135.             }
    136.         }
    137.        
    138.         Debug.DrawRay(ray.origin, ray.direction * capsule.height * jumpRayLength, grounded ? Color.green : Color.red );
    139.  
    140.  
    141.         // add extra gravity
    142.         GetComponent<Rigidbody>().AddForce(Physics.gravity * (advanced.gravityMultiplier - 1));
    143.     }
    144.  
    145.    
    146.     //used for comparing distances
    147.     class RayHitComparer: IComparer
    148.     {
    149.         public int Compare(object x, object y)
    150.         {
    151.             return ((RaycastHit)x).distance.CompareTo(((RaycastHit)y).distance);
    152.         }  
    153.     }
    154.    
    155. }
    156.  
    the next possible one

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class MouseRotator : MonoBehaviour {
    4.    
    5.     // A mouselook behaviour with constraints which operate relative to
    6.     // this gameobject's initial rotation.
    7.    
    8.     // Only rotates around local X and Y.
    9.    
    10.     // Works in local coordinates, so if this object is parented
    11.     // to another moving gameobject, its local constraints will
    12.     // operate correctly
    13.     // (Think: looking out the side window of a car, or a gun turret
    14.     // on a moving spaceship with a limited angular range)
    15.    
    16.     // to have no constraints on an axis, set the rotationRange to 360 or greater.
    17.  
    18.     public Vector2 rotationRange = new Vector3(70,70);
    19.     public float rotationSpeed = 10;
    20.     public float dampingTime = 0.2f;
    21.     public bool autoZeroVerticalOnMobile = true;
    22.     public bool autoZeroHorizontalOnMobile = false;
    23.     public bool relative = true;
    24.     Vector3 targetAngles;
    25.     Vector3 followAngles;
    26.     Vector3 followVelocity;
    27.     Quaternion originalRotation;
    28.  
    29.    
    30.     // Use this for initialization
    31.     void Start () {
    32.         originalRotation = transform.localRotation;
    33.     }
    34.    
    35.     // Update is called once per frame
    36.     void Update () {
    37.        
    38.         // we make initial calculations from the original local rotation
    39.         transform.localRotation = originalRotation;
    40.  
    41.         // read input from mouse or mobile controls
    42.         float inputH = 0;
    43.         float inputV = 0;
    44.         if (relative)
    45.         {
    46.            
    47.             inputH = Input.GetAxis("Mouse X");
    48.             inputV = Input.GetAxis("Mouse Y");
    49.            
    50.             // wrap values to avoid springing quickly the wrong way from positive to negative
    51.             if (targetAngles.y > 180) { targetAngles.y -= 360; followAngles.y -= 360; }
    52.             if (targetAngles.x > 180) { targetAngles.x -= 360; followAngles.x-= 360; }
    53.             if (targetAngles.y < -180) { targetAngles.y += 360; followAngles.y += 360; }
    54.             if (targetAngles.x < -180) { targetAngles.x += 360; followAngles.x += 360; }
    55.  
    56.             // with mouse input, we have direct control with no springback required.
    57.             targetAngles.y += inputH * rotationSpeed;
    58.             targetAngles.x += inputV * rotationSpeed;
    59.  
    60.             // clamp values to allowed range
    61.             targetAngles.y = Mathf.Clamp ( targetAngles.y, -rotationRange.y * 0.5f, rotationRange.y * 0.5f );
    62.             targetAngles.x = Mathf.Clamp ( targetAngles.x, -rotationRange.x * 0.5f, rotationRange.x * 0.5f );
    63.  
    64.         } else {
    65.  
    66.             inputH = Input.mousePosition.x;
    67.             inputV = Input.mousePosition.y;
    68.  
    69.             // set values to allowed range
    70.             targetAngles.y = Mathf.Lerp ( -rotationRange.y * 0.5f, rotationRange.y * 0.5f, inputH/Screen.width );
    71.             targetAngles.x = Mathf.Lerp ( -rotationRange.x * 0.5f, rotationRange.x * 0.5f, inputV/Screen.height );
    72.  
    73.  
    74.  
    75.         }
    76.  
    77.  
    78.  
    79.  
    80.  
    81.         // smoothly interpolate current values to target angles
    82.         followAngles = Vector3.SmoothDamp( followAngles, targetAngles, ref followVelocity, dampingTime );
    83.  
    84.         // update the actual gameobject's rotation
    85.         transform.localRotation = originalRotation * Quaternion.Euler( -followAngles.x, followAngles.y, 0 );
    86.        
    87.     }
    88.  
    89.  
    90. }
    thanks
     
  2. BlackMantis

    BlackMantis

    Joined:
    Feb 7, 2010
    Posts:
    1,475
    Hello, I didn't spot anything wrong with the code after a couple eye scrolls lol. Maybe check the project Input @ Edit / Project Settings / Input, to see if the Vertical axis's have had mouse usage added to them, or if they are just using the norm / default arrow keys and WASD.