I have created some code for my unity game. When my player reaches a certain distance to my enemy the enemy goes from idle to run and then when it gets within a closer distance it switches to the attack animation. When it goes from idle to run the animation looks really weird and the enemy floats along the ground and and then plays the run animation.
Can anyone see why?
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
float maxDistance = 15.0f;
float attackDistance = 5.0f;
Animation _animation;
void Start()
{
_animation = GetComponentInChildren();
GameObject playerGameObject = GameObject.FindGameObjectWithTag("Player");
_player = playerGameObject.transform;
_controller = GetComponent();
_animation.CrossFade("idle1_");
}
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) {
_controller.Move(velocity*Time.deltaTime);
_animation.CrossFade("run_");
}
if (Vector3.Distance(_player.position, transform.position) < maxDistance && (Vector3.Distance(_player.position, transform.position) < attackDistance)) {
_animation.CrossFade("hornAttack1_", 0.5f);
}
}
}
↧