Search Unity

2D Racing game, OnTriggers not working but Colliders work

Discussion in '2D' started by RikoF1, Dec 5, 2019.

  1. RikoF1

    RikoF1

    Joined:
    Nov 14, 2019
    Posts:
    2
    Hello all,
    This is my first post here, sorry if I put it in the wrong place.
    So, I'm doing a little uni project which consists on getting a race track with a car doing time trials.

    I was following this tutorial and copied basically everything. The thing is, most of the code does not work.
    Collisions are fine, but everything that involves triggers do not work. My due date is this friday and I'm getting a little desperate because I doubt the code is wrong and there must be something wrong with my project.

    As there are 6 scripts already I added the full project to my google drive, if you could check and point me out in the right track, I'd appreciate.

    EDIT: Basically, the colliders I put for the outside part of the track to slow the player do not work, the oil spill does not make the player spin/slow down, the checkpoints/finish line do not give any debug code (do not work).
     
  2. MisterSkitz

    MisterSkitz

    Joined:
    Sep 2, 2015
    Posts:
    776
    I don't want to download your project. Post your code in here and use code tags to make it more readable. I'm willing to bet that your code is using depreciated source. (Depending on your version of Unity)
    Also, you mention a due date. Is this a school project that you're trying to submit a tutorial project?

    Edit:

    I thought about it. Are you using:

    OnTriggerEnter2D()

    or

    OnTriggerEnter()
     
  3. RikoF1

    RikoF1

    Joined:
    Nov 14, 2019
    Posts:
    2
    CarCollision
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class CarCollision : MonoBehaviour {
    6.  
    7.     CarMovement m_Movement;
    8.  
    9.     private void Awake()
    10.     {
    11.         m_Movement = GetComponent<CarMovement>();
    12.     }
    13.  
    14.     private void OnCollisionEnter2D( Collision2D collision )
    15.     {
    16.         // Debug.Log( "Colliding with " + collision.collider.name + ". Tag: " + collision.collider.tag );
    17.  
    18.         if( collision.collider.CompareTag( "Obstacle" ) == true )
    19.         {
    20.             m_Movement.OnCollideWithObstacle();
    21.         }
    22.     }
    23.  
    24.     private void OnTriggerEnter2D( Collider2D otherCollider )
    25.     {
    26.         if( otherCollider.CompareTag( "Oil" ) == true )
    27.         {
    28.             m_Movement.OnCollideWithOil();
    29.         }
    30.  
    31.         if( otherCollider.CompareTag( "OffCourseArea" ) == true)
    32.         {
    33.             m_Movement.OnEnterOffCourseArea();
    34.         }
    35.     }
    36.  
    37.     private void OnTriggerExit2D( Collider2D otherCollider )
    38.     {
    39.         if( otherCollider.CompareTag( "OffCourseArea" ) == true )
    40.         {
    41.             m_Movement.OnExitOffCourseArea();
    42.         }
    43.     }
    44. }
    45.  
    CarInputBase
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5.     [RequireComponent( typeof( CarMovement))]
    6. public class CarInputBase : MonoBehaviour
    7. {
    8.     CarMovement m_Movement;
    9.  
    10.     private void Awake()
    11.     {
    12.         m_Movement = GetComponent<CarMovement>();
    13.     }
    14.  
    15.     protected void SetSteeringDirection( float steeringDirection )
    16.     {
    17.         m_Movement.SetSteeringDirection( steeringDirection);
    18.     }
    19.  
    20.     protected void SetEnginePower( float enginePower )
    21.     {
    22.         m_Movement.SetEnginePower( enginePower );
    23.     }
    24.  
    25. }
    CarInputKeyboard
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class CarInputKeyboard : CarInputBase {
    6.  
    7.     void Update()
    8.     {
    9.         UpdateSteering();
    10.         UpdateEnginePower();
    11.     }
    12.  
    13.     void UpdateSteering()
    14.     {
    15.         SetSteeringDirection( Input.GetAxisRaw( "Horizontal" ) );
    16.     }
    17.  
    18.     void UpdateEnginePower()
    19.         {
    20.             SetEnginePower ( Input.GetAxisRaw( "Vertical" ) );
    21.         }
    22.  
    23. }
    24.  
    CarMovement
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class CarMovement : MonoBehaviour {
    6.  
    7.     public float MaximumEngineForce;
    8.     public float MaximumReverseEngineForce;
    9.     public float MaximumSteeringTorque;
    10.     public float ReversePower;
    11.     public float Acceleration;
    12.     public float Deceleration;
    13.     public Transform VisualsParent;
    14.     public float SpinningDuration;
    15.     public int SpinningRotations;
    16.  
    17.  
    18.     float m_EnginePower = 0f;
    19.     float m_TargetEnginePower = 0f;
    20.     float m_SteeringDirection = 0f;
    21.     float m_CurrentMaximumEnginePower = 1f;
    22.     bool m_IsSpinning = false;
    23.  
    24.     Rigidbody2D m_Body;
    25.  
    26.     private void Awake()
    27.     {
    28.         m_Body = GetComponent<Rigidbody2D>();
    29.     }
    30.  
    31.     private void Update()
    32.     {
    33.         UpdateEnginePower();
    34.     }
    35.  
    36.     void UpdateEnginePower()
    37.     {
    38.         float acceleration = Acceleration;
    39.  
    40.         if( m_TargetEnginePower == 0f )
    41.         {
    42.             acceleration = Deceleration;
    43.         }
    44.  
    45.         float targetEnginePower = m_TargetEnginePower * m_CurrentMaximumEnginePower;
    46.  
    47.         m_EnginePower = Mathf.MoveTowards( m_EnginePower, targetEnginePower, acceleration * Time.deltaTime );
    48.  
    49.         if( m_IsSpinning == true )
    50.         {
    51.             m_EnginePower = 0f;
    52.         }
    53.     }
    54.  
    55.  
    56.     void FixedUpdate()
    57.     {
    58.         ApplyEngineForce();
    59.         ApplySteeringForce();
    60.     }
    61.  
    62.     void ApplyEngineForce()
    63.     {
    64.         float maximumEngineForce = MaximumEngineForce;
    65.  
    66.         if( m_EnginePower < 0f )
    67.         {
    68.             maximumEngineForce = MaximumReverseEngineForce;
    69.          
    70.         }
    71.  
    72.         m_Body.AddForce( transform.up * m_EnginePower * maximumEngineForce, ForceMode2D.Force );
    73.      
    74.     }
    75.  
    76.     void ApplySteeringForce()
    77.     {
    78.         m_Body.AddTorque( m_SteeringDirection * MaximumSteeringTorque, ForceMode2D.Force );
    79.     }
    80.  
    81.     public void SetEnginePower( float enginePower )
    82.     {
    83.         m_EnginePower = Mathf.Clamp( enginePower, -1f , 1f);
    84.     }
    85.  
    86.     public void SetSteeringDirection( float steeringDirection )
    87.     {
    88.         m_SteeringDirection = Mathf.Clamp( steeringDirection, -1f, 1f);
    89.     }
    90.  
    91.     void StartSpinning()
    92.     {
    93.         if( m_IsSpinning == true )
    94.         {
    95.             return;
    96.         }
    97.  
    98.         StartCoroutine( SpinningRoutine() );
    99.     }
    100.         IEnumerator SpinningRoutine()
    101.         {
    102.             m_IsSpinning = true;
    103.             float spinningTime = 0f;
    104.  
    105.             while ( spinningTime < SpinningDuration )
    106.             {
    107.                 float spinningProgress = spinningTime / SpinningDuration;
    108.                 spinningTime += Time.deltaTime;
    109.  
    110.                 VisualsParent.transform.localRotation = Quaternion.Euler( 0f, 0f, spinningProgress * SpinningRotations * 360f );
    111.  
    112.                 yield return null;
    113.             }
    114.  
    115.             VisualsParent.transform.localRotation = Quaternion.identity;
    116.             m_IsSpinning = false;
    117.          
    118.         }
    119.  
    120.     public void OnCollideWithObstacle()
    121.     {
    122.         m_EnginePower = 0f;
    123.     }
    124.  
    125.     public void OnCollideWithOil()
    126.     {
    127.         m_EnginePower = 0f;
    128.         StartSpinning();
    129.     }
    130.  
    131.     public void OnEnterOffCourseArea()
    132.     {
    133.         m_CurrentMaximumEnginePower = 0.1f;
    134.     }
    135.  
    136.     public void OnExitOffCourseArea()
    137.     {
    138.         m_CurrentMaximumEnginePower = 1f;
    139.     }
    140. }
    LapLine
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class LapLine : MonoBehaviour {
    6.  
    7.     public int Index;
    8.  
    9.     LapManager m_LapManager;
    10.  
    11.     private void Awake()
    12.     {
    13.         m_LapManager = GetComponentInParent<LapManager>();
    14.     }
    15.  
    16.  
    17.     private void OnTriggerEnter2D ( Collider2D otherCollider )
    18.     {
    19.             if( otherCollider.CompareTag( "Car" ) == true )
    20.             {
    21.                 m_LapManager.OnLapLinePassed( Index );
    22.             }
    23.     }
    24.  
    25. }
    26.  
    LapManager
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class LapManager : MonoBehaviour {
    6.  
    7.     public float CurrentLapTime
    8.     {
    9.         get
    10.         {
    11.             if( m_IsLapStarted == false )
    12.             {
    13.                 return 0f;
    14.             }
    15.          
    16.             return Time.realtimeSinceStartup - m_CurrentLapStartTime;
    17.      
    18.         }
    19.     }
    20.  
    21.     public float LastLapTime { get; private set; }
    22.     public float BestLapTime { get; private set; }
    23.  
    24.     bool m_IsLapStarted = false;
    25.     float m_CurrentLapStartTime;
    26.     int m_LastLapLineIndex = 0;
    27.     int m_HighestLapLine;
    28.  
    29.     private void Start()
    30.     {
    31.         m_HighestLapLine = GetHighestLapLine();
    32.     }
    33.  
    34.     int GetHighestLapLine()
    35.     {
    36.         m_HighestLapLine = 0;
    37.         LapLine[] lapLines = GetComponentsInChildren<LapLine>();
    38.  
    39.         for( int i = 0; i < lapLines.Length; ++i )
    40.         {
    41.             m_HighestLapLine = Mathf.Max(lapLines[ i ].Index);
    42.         }
    43.  
    44.         return m_HighestLapLine;
    45.     }
    46.  
    47.     public void OnLapLinePassed ( int index )
    48.     {
    49.         if( index == 0 )
    50.         {
    51.             if( m_IsLapStarted == false || m_LastLapLineIndex == m_HighestLapLine )
    52.             {
    53.              
    54.                 OnFinishLinePassed();
    55.             }
    56.         }
    57.         else
    58.         {
    59.             {
    60.                 if( index == m_LastLapLineIndex + 1)
    61.                 {
    62.                     m_LastLapLineIndex = index;
    63.              
    64.                 }
    65.             }
    66.         }
    67.     }
    68.  
    69.     void OnFinishLinePassed()
    70.     {
    71.         if( m_IsLapStarted == true )
    72.             {
    73.                 LastLapTime = Time.realtimeSinceStartup - m_CurrentLapStartTime;
    74.  
    75.                 if( LastLapTime < BestLapTime || BestLapTime == 0f )
    76.                 {
    77.                     BestLapTime = LastLapTime;
    78.                 }
    79.             }
    80.  
    81.             m_IsLapStarted = true;
    82.             m_CurrentLapStartTime = Time.realtimeSinceStartup;
    83.     }
    84. }
    LapManagerUI
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using System.Collections;
    4.  
    5. [RequireComponent( typeof(LapManager))]
    6. public class LapManagerUI : MonoBehaviour {
    7.  
    8.     public Text LapTimeInfoText;
    9.  
    10.     LapManager m_LapManager;
    11.  
    12.     private void Awake()
    13.     {
    14.         m_LapManager = GetComponent<LapManager>();
    15.     }
    16.  
    17.     void Update()
    18.     {
    19.  
    20.     }
    21.  
    22.     void UpdateLapTimeInfoText()
    23.     {
    24.         LapTimeInfoText.text = "Current:  " + SecondsToTime( m_LapManager.CurrentLapTime ) + "\n"
    25.             + "Last: "+ SecondsToTime( m_LapManager.CurrentLapTime ) + "\n"
    26.             + "Best: " + SecondsToTime( m_LapManager.BestLapTime ) + "";
    27.     }
    28.  
    29.     string SecondsToTime( float seconds )
    30.     {
    31.         int displayMinutes = Mathf.FloorToInt( seconds / 60f );
    32.         int displaySeconds = Mathf.FloorToInt( seconds % 60f );
    33.         int displayFractionSeconds = Mathf.FloorToInt( ( seconds - displaySeconds ) * 100f );
    34.  
    35.         return displayMinutes + ":" + displaySeconds.ToString( "00" ) + ":" + displayFractionSeconds.ToString( "00" );
    36.     }  
    37.      
    38. }
    39.  
    SceneSwitch
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6.  
    7. public class SceneSwitch : MonoBehaviour {
    8.  
    9. void OnTriggerEnter(Collider other)
    10. {
    11. if (other.CompareTag ("Car"))
    12.     {
    13.        SceneManager.LoadScene (1);
    14.       }
    15.  
    16.     }
    17. }
    18.  
    EDIT: My next scene triggers work now.
     
    Last edited: Dec 5, 2019
  4. MisterSkitz

    MisterSkitz

    Joined:
    Sep 2, 2015
    Posts:
    776
    Usually when the colliders don't work it is because the tag is misspelled or improperly punctuated. For example, if you put a tag on your car named "car" and you type in if(other.CompareTag("Car")) then the collider will ignore the collision.

    I don't see anything in your code that looks like it would cause it to ignore the check. I can only assume that if nothing is misspelled, then maybe you are using a Kinematic Ridgidbody2D? I looked at your movement script, another thing that can cause this is movement with Transform.translate. However, this isn't the case because you're using add force. At first I thought maybe ForceType.Force as opposed to .Impulse could be the issue, however, I think .Force calculates force of seconds based upon mass and .Impulse calculates by frame, also affected by mass, but also timestep. So I really don't understand your problem you're having.

    Is it an issue with layer mask? Possibly your car, in that scene has its layer mask set to ignore the colliders layer mask???
     
  5. MisterSkitz

    MisterSkitz

    Joined:
    Sep 2, 2015
    Posts:
    776
    I want you to put a Debug.Log() in here for me. I need to know if this is responding to your collision or not.

    Lapline script:

    Code (CSharp):
    1. private void OnTriggerEnter2D ( Collider2D otherCollider )
    2.     {
    3.             if( otherCollider.CompareTag( "Car" ) == true )
    4.             {
    5.                 m_LapManager.OnLapLinePassed( Index );
    6.                // Add this (below)
    7.                Debug.Log("Lap Line touched");
    8.             }
    9.     }
    Do this in all of your OnTrigger functions. Screen shot your results and post them here.