移动时发生的恒定动画

本文关键字:动画 移动 | 更新日期: 2023-09-27 17:54:10

我有以下代码,但我有一些问题。每次更新被调用,角色移动到我给他的点。但是当我用鼠标点击地面时,我只是给他一个点,当我试图让它动画角色时,问题就开始了。

如果我将动画的值传递给clickToMove()方法,它将始终播放动画,即使我们不移动。如果我将clickToMove放置在"如果点击"中,角色将传送而不是移动。我不能认为在一种方式来做动画正确,只有当对象正在移动,并回到空闲时,当它停止,即使clickToMove()一直在播放。

using UnityEngine;
using System.Collections;
public class ClickScript : MonoBehaviour
{
public float moveSpeed;
public float minDistance;
Vector3 mouseClick; //Creates a variable to save the constant of the hit from raycast
private Animator anim;
private Rigidbody rigidB;

// Use this for initialization
void Start()
{
    anim = GetComponent<Animator>();
    rigidB = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
    if (Input.GetMouseButtonDown(1))//If clicked
    {
        clickPosition(); //Gets the click position
    }
    if (Vector3.Distance(transform.position, mouseClick) > minDistance) //If the click distance is bigger than the minimal
    {
        //It is allways moving, but since there's no click position it doesn't move when not clicked
        clickToMove();
    }
}
void clickPosition()//This function throw a raycast on the ground and save the position on mouseClick to make the char move to there
{
        RaycastHit clickHit; //creates a constant with the infos from the raycast
        Ray mouseClickPosition = Camera.main.ScreenPointToRay(Input.mousePosition); //creates a constant to save the mouse position
        if (Physics.Raycast(mouseClickPosition, out clickHit, 100.00f))//throw a raycast returning the mouse position and more infos
        {
            Debug.Log("Click at " + clickHit.point); //Show where were clicked
            mouseClick = clickHit.point;//mouseClick receive the position of the click
        }
}
void clickToMove() //this function make the player look at the click and move to mouseClick
{
    mouseClick.y = transform.position.y; //get rid of the y to fix rotation bugs
    transform.LookAt(mouseClick);//look at the poit you clicked        
    transform.position = Vector3.MoveTowards(transform.position, mouseClick, moveSpeed * Time.deltaTime);//move to the clickpoint
}
}

移动时发生的恒定动画

这样怎么样?

bool _isAnimating = false;
// Update is called once per frame
void FixedUpdate()
{
    if (Input.GetMouseButtonDown(1))//If clicked
    {
        clickPosition(); //Gets the click position
        //start animation here!!!
        //animator.SetBool("bWalk", false);
        //and set animation state to true
        _isAnimating = true;
    }
    if (Vector3.Distance(transform.position, mouseClick) > minDistance)
    {
        clickToMove();
    }
    else if(_isAnimating)
    {
        //turn off the animation here!!!
        //animator.SetBool("bStop", false);
        //and set to false
        _isAnimating = false;
    }
}