Search Unity

Enemy Animation Script (C# Help)

Discussion in 'Scripting' started by Legosdoctor, Oct 8, 2015.

  1. Legosdoctor

    Legosdoctor

    Joined:
    Jul 23, 2015
    Posts:
    21
    How do I get my Enemy to use a walking animation when its moving? I have a script that makes it follow the player, but I don't know how to incorporate a animation into it? Any ideas?
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Have you set up your Animator yet? That's the first step (read tutorials on the Animator if you have to). Make sure that your animator has a "float" type variable representing forward motion. Let's call it "MovementForward". I recommend you use that float in a blend tree that blends between your standing and walking (and running, if you have it) animations.

    In code, you will want to compare your position to your previous position, and then set MovementForward to the difference. BUT, you don't want this to just be the change in position; you really want it to be the speed. I recommend you also put some smoothing on that value using Mathf.Lerp or the animation may look jerky.

    That part of the code will probably look like:
    Code (csharp):
    1. Animator myAnimator;
    2. void Awake() {
    3. myAnimator = GetComponent<Animator>();
    4. }
    5. float smoothedSpeed = 0f;
    6. void LateUpdate() {
    7. float positionChange = (transform.position - lastFramePosition).magnitude;
    8. float thisFrameSpeed = positionChange / Time.deltaTime;
    9. smoothedSpeed = Mathf.Lerp(smoothedSpeed, thisFrameSpeed, 0.5f);
    10. myAnimator.SetFloat("MovementForward", smoothedSpeed);
    11. lastFramePosition = transform.position;
    12. }
     
  3. Sykoo

    Sykoo

    Joined:
    Jul 25, 2014
    Posts:
    1,394
    Do you use Legacy or Animator system?
    http://docs.unity3d.com/Manual/Animations.html

    In Unity 5, the API changed a lot, meaning you now have to usually GetComponent from objects.
    So, just like @StarManta stated in his code snippet,
    Code (CSharp):
    1. Animator myAnimator;
    2. void Start()
    3. {
    4.    myAnimator = GetComponent<Animator>();
    5. }
    is required in case you use Animator system.
    If you use Legacy animation system, then you need
    Code (CSharp):
    1. Animation myAnimation;
    2. void Start()
    3. {
    4.    myAnimation = GetComponent<Animation>();
    5. }