首页 > 解决方案 > 我很难找到一种方法来跟踪我的角色是否静止以及他们在看什么方向

问题描述

我最近让我的角色移动工作得很好,我现在正试图将它与我设置的动画很好地结合起来。

有没有办法跟踪角色是否静止? 我找到了一种方法来跟踪这个使用:

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");
    }
}

标签: c#unity3d

解决方案


这是用于方向检查:

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;
        }
    }

推荐阅读