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

Check how long a Ray is hitting an object

Discussion in 'Scripting' started by unitynoob24, Jan 20, 2019.

  1. unitynoob24

    unitynoob24

    Joined:
    Dec 27, 2014
    Posts:
    398
    Hey guys.

    I am wondering what the best way would be to check how long a ray is hitting an object. Basically I want to fire some logic, but only after a ray has collided with an object for X seconds.

    Thanks!
     
  2. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    Raycasts live from frame to frame they don't have a concept of time, you have to tally(is that the right spelling?, count) them yourself.
    Keep a variable 'start' when the first one hits, something like this
    Code (CSharp):
    1. float hitTime;
    2. float maxTime;
    3. Collider col;
    4.  
    5. void Foo(){
    6. Raycast hit;
    7. if(Physics.Raycast( do your ray, out hit)){
    8.  
    9. if( hit.collider == col){ // this is the same collider from last frame
    10. if(startTime + maxTime > Time.time){//check if time has passed, meaning we were pointing at collider col for maxTime
    11. //Do w/e
    12. }
    13.  
    14. }else{
    15. startTime = Time.time;
    16. col = hit.collider;
    17. }
    18. } else{
    19. startTime = 0.0f;
    20. col = null;
    21. }
    22. }
    Oh S*** it ain't formatted, oh well.. :shrug: