Search Unity

Make a "Guard" Script?

Discussion in 'Scripting' started by M2aProductions, Nov 27, 2014.

  1. M2aProductions

    M2aProductions

    Joined:
    Jul 23, 2013
    Posts:
    7
    Hello. I am making a game, And in the game, there are supposed to be enemies that follow you and when you touch them, you die. Now I already have a script so the enemies follow you. It's this one :

    vartarget : Transform;
    varmoveSpeed = 3;
    varrotationSpeed = 3;

    varmyTransform : Transform;

    functionAwake()
    {
    myTransform = transform;
    }

    functionStart()
    {
    target = GameObject.FindWithTag("Player").tranform;

    }
    functionUpdate () {
    myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
    Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);

    //movetowardstheplayer
    myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;


    }

    But I want to make the enemy only start following the player if the player is close to it. I know you're supposed to use a Vector3.distance script, but I am a total noob at these things. Help would be greatly appreciated!
     
  2. Tomnnn

    Tomnnn

    Joined:
    May 23, 2013
    Posts:
    4,148
    Make a 'followPlayer' boolean in your variable declarations. Then run a distance check in your update function. Add an if statement around your movement code so it only runs if the followPlayer boolean is true.

    Code (CSharp):
    1. bool followPlayer = false;//defined somewhere
    2. float dist = 1.5f;// how close you get before they follow
    3.  
    4. if(followPlayer == false && Vector3.Distance(player.transform.position, transform.position) < dist)
    5. {
    6.     followPlayer = true;
    7. }
    Code (CSharp):
    1. if(followPlayer)
    2. {
    3.     myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
    4. }
     
  3. M2aProductions

    M2aProductions

    Joined:
    Jul 23, 2013
    Posts:
    7
    Um... Sorry but I don't know Boolean, is it possible in Javascript?
     
  4. QualixInteractive

    QualixInteractive

    Joined:
    Nov 2, 2013
    Posts:
    9
    Hi,

    Boolean is a basic variable type. It is a simple "True" or "False" variable. In order to call a new boolean, simply add this :

    var distPlayer : boolean = false;

    And to use it, remember that there is no other value than true or false.

    Hope I helped.

    Dave