为什么我的角色不能总是播放他的动画?

问题描述 投票:0回答:1

让我解释一下。我为您在游戏中控制的角色编写了代码。基本上,它检查游戏对象的当前精灵是否为main_0(它没有移动),然后如果按箭头,它可以移动并运行动画。这里的问题是,当我执行游戏并尝试按键时,仅在50%的情况下,movin动画才起作用。有人知道发生了什么吗?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

 public class MainController : MonoBehaviour
{
string disfname;
void Start()
{

}
void Update()
{
    disfname = gameObject.GetComponent<SpriteRenderer>().sprite.name;
    gameObject.GetComponent<Animator>().SetBool("moving", false);
    if (Input.GetKeyDown("right") && disfname == "main_0")
    {
        gameObject.GetComponent<Animator>().SetBool("moving", true);
        gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector3(300000 * Time.deltaTime, 0, 0));
        gameObject.transform.rotation = Quaternion.AngleAxis(0, Vector3.up);
    }
    if (Input.GetKeyDown("left") && disfname == "main_0")
    {
        gameObject.GetComponent<Animator>().SetBool("moving", true);
        gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector3(-300000 * Time.deltaTime, 0, 0));
        gameObject.transform.rotation = Quaternion.AngleAxis(180, Vector3.up);
    }
    if (Input.GetKey("up"))
    {
        gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector3(0, 2000 * Time.deltaTime, 0));
    }
    if (Input.GetKey("down"))
    {
        gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector3(0, -1000 * Time.deltaTime, 0));
    }
}

}

也要先谢谢您,我的英语不好:D

c# unity3d
1个回答
0
投票

您要在Update的开头停止动画,然后在之后立即重新启动动画。这是您的解决方案:

void Update()
{
   disfname = gameObject.GetComponent<SpriteRenderer>().sprite.name;

   if (Input.GetKeyDown("right") && disfname == "main_0")
   {
      gameObject.GetComponent<Animator>().SetBool("moving", true);
      gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector3(300000 * Time.deltaTime, 0, 0));
      gameObject.transform.rotation = Quaternion.AngleAxis(0, Vector3.up);
   }
   else if (Input.GetKeyDown("left") && disfname == "main_0")
   {
      gameObject.GetComponent<Animator>().SetBool("moving", true);
      gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector3(-300000 * Time.deltaTime, 0, 0));
      gameObject.transform.rotation = Quaternion.AngleAxis(180, Vector3.up);
   }
   else
   {
      gameObject.GetComponent<Animator>().SetBool("moving", false);
   }

   // Some other stuff...
}
© www.soinside.com 2019 - 2024. All rights reserved.