Search Unity

Enemy animation based on distance in mecanim

Discussion in 'Animation' started by Soumikbhat, May 25, 2014.

  1. Soumikbhat

    Soumikbhat

    Joined:
    Nov 23, 2013
    Posts:
    110
    I am using mecanim system for animation in unity..I've created a script that measures the distance between the player and the enemy..

    Now I've walk animations dragged into my animator window, created transitions from idle to those "walk" animations and applied the animator controller to my enemy character.

    What I want over here is that the enemy would perform the walk animation in the direction of the player. Need help in fixing this direction stuff. :(

    My script that I am using is this :

    Code (csharp):
    1. /*#pragma strict
    2.  
    3. function Start () {
    4.  
    5. }
    6.  
    7. function Update () {
    8.  
    9. }*/
    10. #pragma strict
    11. internal var animator : Animator;
    12. var hor : float;
    13. var ver : float;
    14. var distance : float;
    15. var player : GameObject;
    16. var enemy : GameObject;
    17.  
    18. function Start () {
    19. player = GameObject.Find("Mainplayer");
    20.  
    21.          enemy = GameObject.Find("soldier");
    22. animator=GetComponent(Animator);
    23. }
    24.  
    25. function Update () {
    26. distance = Vector3.Distance(player.transform.position,enemy.transform.position);
    27.  
    28.  
    29. }
    30. function FixedUpdate() {
    31. distance = Vector3.Distance(player.transform.position,enemy.transform.position);
    32. animator.SetFloat("Walk", distance);
    33.  
    34.  
    35.  
    36.  
    37.  
    38.  
    39.  
    40.  
    41. }
    42.  
     
    Last edited: May 25, 2014
  2. TMPxyz

    TMPxyz

    Joined:
    Jul 20, 2012
    Posts:
    766
    you mean turn the enemy to face your player?

    Assume they're on the same height,

    var towardPlayer = (player.transform.position - enemy.transform.position).normalized;
    enemy.transform.rotation = Quaternion.LookRotation(towardPlayer);
     
  3. Soumikbhat

    Soumikbhat

    Joined:
    Nov 23, 2013
    Posts:
    110