Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct here to familiarize yourself with the rules and how to post constructively.

  2. Unity 2022.1 is now available as the latest Tech release.
    Dismiss Notice
  3. Improve your project's performance with our new guide on profiling in Unity.
    Dismiss Notice

Resolved Math problem

Discussion in 'Scripting' started by Saw9yer, Dec 29, 2021.

  1. Saw9yer

    Saw9yer

    Joined:
    Sep 19, 2020
    Posts:
    51
    Hello everyone,
    I have a raycast and a hit point.
    I want my bullet stop when it overtakes the hitpoint.

    So i did the code below :
    Code (CSharp):
    1. if (hasHitPoint == true)// if i have a hitpoint
    2.             {
    3.                 float distX = (hitPoint.x) - (transform.position.x);
    4.                 float distY = (hitPoint.y) - (transform.position.y);
    5.  
    6.                 if ((distX <= 0 || distY <= 0))
    7.                 {
    8.                     transform.position = hitPoint;
    9.                     stateBullet = State.Collision;
    10.                 }
    11.                 else
    12.                 {
    13.                     transform.Translate(speed * Time.deltaTime * normalizeDirection);
    14.                 }
    15.             }
    This code works well when for exemple transform.position.x<hitPoint.x.
    But if transform.position.x>hitPoint.x my object just teleport.
    I understand why but i can't find a way to test if my bullet overtakes the hitpoint.
    I need to find a way to always have a positive distX unless it overtakes the hitpoint.
    But maybe there is an other way to handle this?

    Can you help me?
     
  2. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    634
    Just need to make a small correction to properly calculate the distance no matter which direction hitPoint is relative to the transform.

    Code (CSharp):
    1. if (hasHitPoint == true)
    2. {
    3.     float remainingDistance = Vector3.Distance(hitPoint, transform.position);
    4.     float moveDistance = speed * Time.deltaTime;
    5.  
    6.     if(remainingDistance <= moveDistance)
    7.     {
    8.         transform.position = hitPoint;
    9.         stateBullet = State.Collision;
    10.     }
    11.     else
    12.     {
    13.         transform.Translate(moveDistance * normalizeDirection);
    14.     }
    15. }
     
    Saw9yer likes this.
  3. Saw9yer

    Saw9yer

    Joined:
    Sep 19, 2020
    Posts:
    51
    Thank you
     
    SisusCo likes this.
unityunity