Search Unity

Question How Can I Fix the Delay?

Discussion in 'Scripting' started by MuhammetUgurBozdemir, Apr 21, 2021.

  1. MuhammetUgurBozdemir

    MuhammetUgurBozdemir

    Joined:
    Mar 6, 2021
    Posts:
    45
    I add raycast front of the cars, If ray touched any car in front car will brake.But after braking cars waiting a bit to move again.


    Code (CSharp):
    1.    public void Start()
    2.     {
    3.         speed = Random.Range(25f, 40f);
    4.      
    5.  
    6.     }
    7.  
    8.     // Update is called once per frame
    9.     public void Update()
    10.     {
    11.        RaycastHit hit;
    12.        if(Physics.Raycast(transform.position,transform.forward,out hit, 20))
    13.         {
    14.             if (hit.collider.tag == "EnemyCar")
    15.             {
    16.                 Debug.DrawLine(transform.position, hit.point);
    17.                 hitDistance = hit.distance / 20;
    18.             }
    19.             else
    20.             {
    21.                 hitDistance = 1;
    22.             }
    23.         }
    24.  
    25.         transform.Translate(0, 0, 1 * speed * Time.deltaTime * hitDistance, Space.World);
    26.  
    27.     }
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    The way your code is written, hitDistance doesn't reset to a value of 1f until you get a Raycast hit on an object not tagged "EnemyCar". I believe if Raycast returns false, you need to set hitDistance to 1.

    Code (CSharp):
    1.    public void Start()
    2.     {
    3.         speed = Random.Range(25f, 40f);
    4.    
    5.  
    6.     }
    7.  
    8.     // Update is called once per frame
    9.     public void Update()
    10.     {
    11.        RaycastHit hit;
    12.        if(Physics.Raycast(transform.position,transform.forward,out hit, 20))
    13.         {
    14.             if (hit.collider.tag == "EnemyCar")
    15.             {
    16.                 Debug.DrawLine(transform.position, hit.point);
    17.                 hitDistance = hit.distance / 20;
    18.             }
    19.             else
    20.             {
    21.                 hitDistance = 1;
    22.             }
    23.         }
    24.         else
    25.         {
    26.             hitDistance = 1;
    27.         }
    28.  
    29.         transform.Translate(0, 0, 1 * speed * Time.deltaTime * hitDistance, Space.World);
    30.  
    31.     }
    I'd probably rewrite the above to not need to set hitDistance in 2 places, but you get the idea. Give it a try, see if it resolves the problem.
     
    MuhammetUgurBozdemir likes this.
  3. MuhammetUgurBozdemir

    MuhammetUgurBozdemir

    Joined:
    Mar 6, 2021
    Posts:
    45
    Yes, It is worked.Thank you so much.