我最近讓我的角色運動作業得非常好,我現在正試圖將它與我設定的影片很好地結合起來。
有沒有辦法跟蹤角色是否靜止? 我找到了一種使用以下方法進行跟蹤的方法:
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");
}
}
uj5u.com熱心網友回復:
這IsSleeping很可能是一個不好的指標。Afaik 剛體在靜止一段時間后根據您的物理設定進入睡眠狀態。
你寧愿使用的是簡單地使用
// In general it is more efficient to check the sqrMagnitude than the magnitude
// especially if you do it each frame
ani.SetBool("Stationary", Mathf.Approximately(rb.velocity.sqrMagnitude, 0));
這將直接檢查剛體當前是否正在移動。
如果某個運動閾值足夠精確,您也可以使用
[Tooltip ("Below this absolute movement speed the object is considered stationary")]
public float stationaryThreshold = 0.01f;
private float squaredStationaryThreshold;
void Awake()
{
squaredStationaryThreshold = stationaryThreshold * stationaryThreshold;
}
然后檢查
ani.SetBool("Stationary", rb.velocity.sqrMagnitude <= squaredStationaryThreshold);
uj5u.com熱心網友回復:
這是用于方向檢查:
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;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/347450.html
下一篇:跳躍沒有在Y軸上移動角色
