c# - 我很难找到一种方法来跟踪我的角色是否静止以及他们在看什么方向
问题描述
我最近让我的角色移动工作得很好,我现在正试图将它与我设置的动画很好地结合起来。
有没有办法跟踪角色是否静止? 我找到了一种方法来跟踪这个使用:
ani.SetBool("Stationary", rb.IsSleeping());
但是,对于我需要的内容,这似乎更新得很慢,因为角色 X 轴在释放移动键后会持续更新大约半秒。有没有更好的方法来检查一个静止的角色,它会在角色完全停止之前认为是静止的?
有没有办法跟踪角色所面对的方向并让他们即使停止移动也保持朝那个方向?
这是我的完整代码供参考;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KittenController2 : MonoBehaviour
{
Rigidbody2D rb;
Animator ani;
public float speed;
public float jumpForce;
private float direction = 0f;
void Start()
{
rb = GetComponent<Rigidbody2D>();
ani = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
direction = Input.GetAxis("Horizontal");
ani.SetBool("Stationary", rb.IsSleeping());
if (direction > 0f)
{
rb.velocity = new Vector2(direction * speed, rb.velocity.y);
ani.SetFloat("Move X", direction);
}
else if (direction < 0f)
{
rb.velocity = new Vector2(direction * speed, rb.velocity.y);
ani.SetFloat("Move X", direction);
}
else
{
rb.velocity = new Vector2(0, rb.velocity.y);
}
if (Input.GetKeyDown(KeyCode.Space))
{
Jump();
}
}
void FixedUpdate()
{
}
void Jump()
{
rb.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
ani.SetTrigger("Jump");
}
}
解决方案
这是用于方向检查:
private bool facingRight; // serialize this at top
private void FacingRight() // call this in the update function
{
if ((facingRight == true) && ((Input.GetKey(KeyCode.LeftArrow))|| (Input.GetKey(KeyCode.A)))) // keys you are pressing to move towards left
{
transform.Rotate(0, 180, 0);
facingRight = false;
}
else if ((facingRight == false) && ((Input.GetKey(KeyCode.RightArrow) || (Input.GetKey(KeyCode.D))))) // again the keys you are pressing for the movement to right
{
transform.Rotate(0, 180, 0);
facingRight = true;
}
}
推荐阅读
- sql-server - 使用 RANK() 或 DENSE_RANK() 按 Rank 获取下一个值
- elasticsearch - Elasticsearch - 索引之间的关联计数?
- android - 我的应用不在 Google Play 商店中,我可以让它自动更新吗?
- rstudio - 如何告诉闪亮服务器和 rstudio 服务器使用哪个版本的 R?
- google-admin-sdk - Google Meet API 错误:Python 得到了一个意外的关键字参数
- django - URL 不断添加反斜杠 Django
- pine-script - 只有在蜡烛关闭 5 分钟后才需要触发入场警报
- typescript - 如何解决“类型循环引用自身错误”?
- while-loop - Nim 中的迭代器生成函数:分配迭代器时工作,直接调用时卡住
- reactjs - React 测试模拟实现一,使用模拟函数