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

Help (Newb) AI Follow

Discussion in 'Scripting' started by Fake Cake, Sep 16, 2012.

  1. Fake Cake

    Fake Cake

    Joined:
    Aug 5, 2012
    Posts:
    4
    I'm having trouble with making a cube follow me. It targets me, but it doesn't translate to the player's position. Code below.





    var target : Transform;

    var moveSpeed = 3;

    var rotationSpeed = 3;

    var myTransform = Transform;



    function Awake()

    {

    myTransform = Transform;

    }



    function Start()

    {

    target = GameObject.FindWithTag("Player").transform;

    }



    //The actual "look at" and "translate to" code is below. This is were the problem is.





    function Update(){

    transform.LookAt(Vector3(target.position.x, transform.position.y, target.position.z));



    myTransform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);

    }
     
  2. Velo222

    Velo222

    Joined:
    Apr 29, 2012
    Posts:
    1,437
    I'm kind of a newb too, so don't hate me if this doesn't work. But it's something to try at least. Somehow you have to translate (or rigidbody move) the cube to your position. Try this maybe:






    I don't think you need to set "myTransform = Transform;" for anything yet really. Maybe try something like above.

    Good luck :)

    Gah, actually I don't think that will work. It gives you the direction, but not the distance. That's why I hate using the translate function. I use something like this (but it requires a rigidbody be attached to the gameobject) :

    "target.rigidbody.MovePosition (rigidbody.position + dir);" where direction is a Vector3 position.
     
    Last edited: Sep 16, 2012
  3. suctioncup

    suctioncup

    Joined:
    May 19, 2012
    Posts:
    273
    Code (csharp):
    1. #pragma strict
    2.  
    3. var target : Transform; //The thing we will be looking towards and following
    4. var speed : float = 2; //Movement speed
    5. private var pos : Transform;
    6.  
    7. function Update()
    8. {
    9.     pos = this.transform; //Set pos to the position of the gameobject with this script
    10.     transform.LookAt(target); //Look at the target
    11.     pos.position += pos.forward * speed * Time.deltaTime; //Move forward
    12. }
    Just slap this code on your enemy, change set target as your target, and fiddle with speed to get the right speed for you.

    Also, try to use the code tags when posting code
     
    Last edited: Sep 16, 2012