Ben Hathaway
Ben Hathaway

Reputation: 356

Blending an animation in Unity

I have a script at the moment, that when the player is within a certain distance from a deer the deer will run and attack my player. I have it idle and then use an if statement to change its animation to run. However i want to then blend it to hornAttack1_ when it gets to my player however i can't get this to work. Help is appreciated here is my script.

using UnityEngine;
using System.Collections;

 public class EnemyMovement : MonoBehaviour
 {
 CharacterController _controller;
 Transform _player;

[SerializeField]
    float _moveSpeed = 5.0f;

[SerializeField]
    float _gravity = 2.0f;

    float _yvelocity = 0.0f;
// max distance enemy can be before he moves towards you    
public int maxDistance;


 void Start()
{
        GameObject playerGameObject = GameObject.FindGameObjectWithTag("Player");
 _player = playerGameObject.transform;

 _controller = GetComponent<CharacterController>();

 maxDistance = 15;



 }

 void Update()
 {
        Vector3 direction = _player.position - transform.position;

        transform.rotation = Quaternion.LookRotation(direction);


        Vector3 velocity = direction * _moveSpeed;

        if (!_controller.isGrounded)
        {
            _yvelocity -= _gravity;
        }

        velocity.y = _yvelocity;

        direction.y =0;

        if (Vector3.Distance(_player.position, transform.position) > maxDistance) {
            animation.CrossFade("idle1_");
            }
     if (Vector3.Distance(_player.position, transform.position) < maxDistance) {

        _controller.Move(velocity*Time.deltaTime);
        animation.Blend("run_");
        animation.Blend ("hornAttack1_");

        }

    }


    }

I have tried this

if (Vector3.Distance(_player.position, transform.position) > maxDistance) {
            animation.CrossFade("idle1_");
            }
     if (Vector3.Distance(_player.position, transform.position) < maxDistance) {

        _controller.Move(velocity*Time.deltaTime);
        animation.CrossFade("run_");


        }

    if (Vector3.Distance(_player.position, transform.position) < maxDistance && (Vector3.Distance(_player.position, transform.position) < attackDistance)) {
        animation.Blend("hornAttack1_");
    }
    }

    }

The animation doesnt change and it goes all laggy

Upvotes: 0

Views: 4598

Answers (1)

Zennichimaro
Zennichimaro

Reputation: 5306

You can use Animator Controller for controlling your state with Parameters set to your states such as Idle, Run, Horn Attack, then in your script you just need to call anim.SetTrigger("Run"); when the player is within distance, and then call anim.SetTrigger("Horn Attack"); when it gets to the player

Upvotes: 1

Related Questions