Search Unity

Problem with Follow 2D Target

Discussion in 'Scripting' started by MG, Nov 26, 2014.

  1. MG

    MG

    Joined:
    Nov 10, 2012
    Posts:
    190
    I have this code:


    Code (JavaScript):
    1.  var Player : Transform;
    2. var MoveSpeed = 4;
    3. var MaxDist = 10;
    4. var MinDist = 5;
    5. function Start ()
    6. {
    7. }
    8. function Update ()
    9. {
    10.      transform.position.z = 0;
    11.      transform.rotation.x = 0;
    12.      transform.rotation.y = 0;
    13.      transform.LookAt(Player);
    14.    
    15.      if(Vector2.Distance(transform.position,Player.position) >= MinDist){
    16.    
    17.           transform.position += transform.forward*MoveSpeed*Time.deltaTime;
    18.          
    19.          
    20.           if(Vector3.Distance(transform.position,Player.position) <= MaxDist)
    21.               {
    22.                  //Here Call any function U want Like Shoot at here or something
    23.     }
    24.  
    25.     }
    26. }
    And as soon i start the game, the object, which has this skipped attach to, then the Rotation X = 27,34215 and Rotation Y = 90,000004

    Why?
     
    Last edited: Nov 26, 2014
  2. Heu

    Heu

    Joined:
    Feb 13, 2012
    Posts:
    349
    Mmm, so what's the problem?

    You've used the transform.LookAt function, in which the object will rotate towards your target, in your case the player. This is why your rotations are like that.

    If you don't want to rotate your object right away, put it in a function, or If Statement and call it when you need it.
     
  3. MG

    MG

    Joined:
    Nov 10, 2012
    Posts:
    190
    Heu I want to only rotate it in Z-rotation
     
  4. MG

    MG

    Joined:
    Nov 10, 2012
    Posts:
    190
    And the move toward the target