Search Unity

How to trigger an permanent event?

Discussion in 'Scripting' started by Fillock, Feb 2, 2013.

  1. Fillock

    Fillock

    Joined:
    Mar 18, 2009
    Posts:
    73
    Hi all!

    I am an 3D artist trying to learn coding, I have progress but still on a low level I'm afraid.

    Here I want to open a slowly door with a Raycast, but when I look another way or walk away the door stop opening. How can I change state in the script so the door is triggered, and then continue to open no mather where the player is walking / looking?

    Thanks for any answer!



    var hit : RaycastHit;

    function Update ()
    {
    if (Physics.Raycast (transform.position, transform.forward, hit, 2))
    {
    if(hit.collider.gameObject.tag == "TheDoor" )
    {
    print ("Door is opening");

    var myWall : GameObject = GameObject.Find ("Door");

    myWall.transform.Rotate(Vector3.right * 50 * Time.deltaTime);
    }
    }
    }
     

    Attached Files:

  2. roger0

    roger0

    Joined:
    Feb 3, 2012
    Posts:
    1,208
    The door stops opening when the player walks away because the code to rotate the door is in the if statement that checks to see if something is hitting the raycast. So if the raycast is not intersecting with the door, it wont execute whats in the if statement. Instead, one solution is when the raycast hits the door, have it toggle a boolean instead,then have a separate if statement that checks to see if the boolean is true. And if it is, then is will continue to open the door.

    Here it is (untested code)

    Code (csharp):
    1. var hit : RaycastHit;
    2. var door activated : boolean = false;
    3. function Update ()
    4. {
    5.  
    6. if (Physics.Raycast (transform.position, transform.forward, hit, 2))
    7. {
    8. if(hit.collider.gameObject.tag == "TheDoor" )
    9. {
    10. doorActivated = true;
    11. }
    12. }
    13.  
    14. if(doorActivated == true){
    15.  
    16. print ("Door is opening");
    17.  
    18. var myWall : GameObject = GameObject.Find ("Door");
    19.  
    20. myWall.transform.Rotate(Vector3.right * 50 * Time.deltaTime);
    21. }
    22.  
    23. }
     
  3. Fillock

    Fillock

    Joined:
    Mar 18, 2009
    Posts:
    73
    Thanks!

    I new it wasn't so complicated but I didn't figure out a way to solve it, your code is working and thank to your explanation I also understand what I was doing wrong :)