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

Question 2D Player movement issue

Discussion in 'Scripting' started by BenHenriques, Apr 19, 2021.

  1. BenHenriques

    BenHenriques

    Joined:
    Apr 6, 2021
    Posts:
    44
    If my character is next to a wall and I try to walk in the other direction, it teleports to the other side of the wall.
    I think the issue is in my character controller script and the fliping is at the bottom.
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.Events;
    3.  
    4. public class Character2DController : MonoBehaviour
    5. {
    6.     [SerializeField] private float m_JumpForce = 400f;                          // Amount of force added when the player jumps.
    7.     [Range(0, 1)] [SerializeField] private float m_CrouchSpeed = .36f;          // Amount of maxSpeed applied to crouching movement. 1 = 100%
    8.     [Range(0, .3f)] [SerializeField] private float m_MovementSmoothing = .05f;  // How much to smooth out the movement
    9.     [SerializeField] private bool m_AirControl = false;                         // Whether or not a player can steer while jumping;
    10.     [SerializeField] private LayerMask m_WhatIsGround;                          // A mask determining what is ground to the character
    11.     [SerializeField] private Transform m_GroundCheck;                           // A position marking where to check if the player is grounded.
    12.     [SerializeField] private Transform m_CeilingCheck;                          // A position marking where to check for ceilings
    13.     [SerializeField] private Collider2D m_CrouchDisableCollider;                // A collider that will be disabled when crouching
    14.  
    15.     public ProjectileBehaviour ProjectilePrefab;
    16.     public Transform LaunchOffset;
    17.    
    18.     const float k_GroundedRadius = .2f; // Radius of the overlap circle to determine if grounded
    19.     private bool m_Grounded;            // Whether or not the player is grounded.
    20.     const float k_CeilingRadius = .2f; // Radius of the overlap circle to determine if the player can stand up
    21.     private Rigidbody2D m_Rigidbody2D;
    22.     private bool m_FacingRight = true;  // For determining which way the player is currently facing.
    23.     private Vector3 m_Velocity = Vector3.zero;
    24.  
    25.     [Header("Events")]
    26.     [Space]
    27.  
    28.     public UnityEvent OnLandEvent;
    29.  
    30.     [System.Serializable]
    31.     public class BoolEvent : UnityEvent<bool> { }
    32.  
    33.     public BoolEvent OnCrouchEvent;
    34.     private bool m_wasCrouching = false;
    35.  
    36.     private void Awake()
    37.     {
    38.         m_Rigidbody2D = GetComponent<Rigidbody2D>();
    39.  
    40.         if (OnLandEvent == null)
    41.             OnLandEvent = new UnityEvent();
    42.  
    43.         if (OnCrouchEvent == null)
    44.             OnCrouchEvent = new BoolEvent();
    45.     }
    46.  
    47.     private void FixedUpdate()
    48.     {
    49.         bool wasGrounded = m_Grounded;
    50.         m_Grounded = false;
    51.  
    52.         // The player is grounded if a circlecast to the groundcheck position hits anything designated as ground
    53.         // This can be done using layers instead but Sample Assets will not overwrite your project settings.
    54.         Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround);
    55.         for (int i = 0; i < colliders.Length; i++)
    56.         {
    57.             if (colliders[i].gameObject != gameObject)
    58.             {
    59.                 m_Grounded = true;
    60.                 if (!wasGrounded)
    61.                     OnLandEvent.Invoke();
    62.             }
    63.         }
    64.     }
    65.  
    66.     private void Update()
    67.     {
    68.         if (Input.GetKeyDown(KeyCode.Mouse1))
    69.         {
    70.             Shoot();
    71.         }
    72.     }
    73.  
    74.     void Shoot()
    75.     {
    76.         Instantiate(ProjectilePrefab, LaunchOffset.position, transform.rotation);
    77.     }
    78.  
    79.     public void Move(float move, bool crouch, bool jump)
    80.     {
    81.         if (!crouch)
    82.         {
    83.             if (Physics2D.OverlapCircle(m_CeilingCheck.position, k_CeilingRadius, m_WhatIsGround))
    84.             {
    85.                 crouch = true;
    86.             }
    87.         }
    88.  
    89.         if (m_Grounded || m_AirControl)
    90.         {
    91.  
    92.             if (crouch)
    93.             {
    94.                 if (!m_wasCrouching)
    95.                 {
    96.                     m_wasCrouching = true;
    97.                     OnCrouchEvent.Invoke(true);
    98.                 }
    99.  
    100.                 move *= m_CrouchSpeed;
    101.  
    102.                 if (m_CrouchDisableCollider != null)
    103.                     m_CrouchDisableCollider.enabled = false;
    104.             }
    105.             else
    106.             {
    107.                 if (m_CrouchDisableCollider != null)
    108.                     m_CrouchDisableCollider.enabled = true;
    109.  
    110.                 if (m_wasCrouching)
    111.                 {
    112.                     m_wasCrouching = false;
    113.                     OnCrouchEvent.Invoke(false);
    114.                 }
    115.             }
    116.  
    117.             Vector3 targetVelocity = new Vector2(move * 10f, m_Rigidbody2D.velocity.y);
    118.             m_Rigidbody2D.velocity = Vector3.SmoothDamp(m_Rigidbody2D.velocity, targetVelocity, ref m_Velocity, m_MovementSmoothing);
    119.  
    120.             if (move > 0 && !m_FacingRight)
    121.             {
    122.                 Flip();
    123.             }
    124.             else if (move < 0 && m_FacingRight)
    125.             {
    126.                 Flip();
    127.             }
    128.         }
    129.        
    130.         if (m_Grounded && jump)
    131.         {
    132.             m_Grounded = false;
    133.             m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
    134.         }
    135.     }
    136.    
    137.     private void Flip()
    138.     {
    139.         m_FacingRight = !m_FacingRight;
    140.  
    141.         Vector3 flipped = transform.localScale;
    142.         flipped.z *= -1f;
    143.         transform.localScale = flipped;
    144.  
    145.         transform.Rotate(0f, 180f, 0f);
    146.     }
    147. }
    148.  
    149.  
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    This sounds like some minor logic sensing error. To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run?
    - what are the values of the variables involved? Are they initialized?

    Knowing this information will help you reason about the behavior you are seeing.

    If you are running a mobile device you can also see the console output. Google for how.