【发布时间】:2021-03-29 18:45:39
【问题描述】:
我正在为我正在开发的游戏制作一些动画(仍处于早期阶段,并且是编码新手)。现在我正在尝试使用 bool 来检测玩家是否在跳跃,然后如果它返回 true,那么动画就会播放。
角色控制器:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Character2dController : MonoBehaviour
{
public float MovementSpeed = 8;
public float JumpForce = 5;
public Transform feet;
public bool isJumping;
private Rigidbody2D rb;
public LayerMask groundLayers;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
isJumping = false;
}
// Update is called once per frame
void Update()
{
Jump();
//LR movement
var movement = Input.GetAxis("Horizontal");
transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * MovementSpeed;
isJumping = false;
}
//Jumping
void Jump()
{
if (Input.GetButtonDown("Jump") && IsGrounded())
{
isJumping = true;
rb.AddForce(new Vector2(0, JumpForce), ForceMode2D.Impulse);
}
}
//Grounding
public bool IsGrounded()
{
Collider2D groundCheck = Physics2D.OverlapCircle(feet.position, 0.5f, groundLayers);
if (groundCheck.gameObject != null)
{
return true;
}
return false;
}
}
角色动画:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterAnimation : MonoBehaviour
{
private Animator anim;
private bool isJumping;
private Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
isJumping = GetComponent<Character2dController>().isJumping;
isJumping = false;
}
// Update is called once per frame
void Update()
{
//Walking Anim
if (Input.GetKey("a") || Input.GetKey("d"))
{
anim.SetBool("isWalking", true);
}
else
{
anim.SetBool("isWalking", false);
}
//Character flipping
if (Input.GetKey("a"))
{
transform.localScale = new Vector3(-1, 1, 1);
}
if (Input.GetKey("d"))
{
transform.localScale = new Vector3(1, 1, 1);
}
if(isJumping == true)
{
anim.SetTrigger("Up");
}
}
}
然而,isJumping bool 似乎永远不会变为 true,因此动画永远不会播放。我已经尝试将它放在字符控制器代码中的多个位置,但它们似乎都不起作用。我想知道我是否做错了什么,或者我是否应该使用不同的方式来为玩家跳跃设置动画。 同样,我对编码还很陌生,所以如果有任何问题,请随时告诉我。谢谢!
【问题讨论】:
-
作为一种方法,这是使用状态机模式的理想选择 - 您可以在此处阅读:gameprogrammingpatterns.com/state.html 按照您的方式进行操作的问题是它很快就会变得管理起来太复杂 - 一旦你开始尝试检测你是从陆地还是水中,从站立、行走、跑步等中跳起还是二段跳。