尽管角色始终是固定的,但角色仍停留在其动画师的“ AirLayer”上。我的AirLayer有我的跳跃动画(起飞和着陆),而GroundLayer(BaseLayer)有我的步行动画。当我玩游戏时,由于某种原因,AirLayer始终将其权重设置为1。
我的代码在下面。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewPlayerController : MonoBehaviour
{
private Rigidbody2D myRigidBody;
private Animator anim;
private SpriteRenderer sr;
private bool facingRight;
[SerializeField]
private Transform[] groundPoints;
[SerializeField]
private float groundRadius;
[SerializeField]
private LayerMask whatIsGround;
[SerializeField]
private float movementSpeed;
private bool isGrounded;
private bool jump;
[SerializeField]
private float jumpForce;
[SerializeField]
private GameObject bullet;
// Start is called before the first frame update
void Start()
{
myRigidBody = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
sr = GetComponent<SpriteRenderer>();
}
void Update()
{
HandleInput();
}
// Update is called once per frame
void FixedUpdate()
{
float horizontal = Input.GetAxisRaw("Horizontal");
isGrounded = IsGrounded();
HandleMovement(horizontal);
Flip(horizontal);
HandleLayers();
ResetValues();
}
private void HandleInput()
{
if (Input.GetKeyDown(KeyCode.Space))
{
jump = true;
}
if (Input.GetKeyDown(KeyCode.V))
{
ShootBullet(0);
}
}
private void HandleMovement(float horizontal)
{
if (myRigidBody.velocity.y<0)
{
anim.SetBool("Land", true);
}
myRigidBody.velocity = new Vector2(horizontal * movementSpeed, myRigidBody.velocity.y);
anim.SetFloat("speed", Mathf.Abs(horizontal));
if(isGrounded && jump)
{
isGrounded = false;
myRigidBody.AddForce(new Vector2(0, jumpForce));
anim.SetTrigger("Jump");
}
}
private void Flip(float horizontal)
{
if(horizontal > 0 && !facingRight || horizontal <0 && facingRight)
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
private bool IsGrounded()
{
if (myRigidBody.velocity.y <= 0)
{
foreach (Transform point in groundPoints)
{
Collider2D[] colliders = Physics2D.OverlapCircleAll(point.position, groundRadius, whatIsGround);
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject)
{
anim.ResetTrigger("Jump");
anim.SetBool("Land", false);
return true;
}
}
}
}
return false;
}
private void ResetValues()
{
jump = false;
}
public void ShootBullet(int value)
{
if (facingRight)
{
GameObject tmp = (GameObject)Instantiate(bullet, transform.position, Quaternion.Euler(new Vector3(0,0,-90)));
tmp.GetComponent<BulletBehaviour>().Initialize(Vector2.right);
}
else
{
GameObject tmp = (GameObject)Instantiate(bullet, transform.position, Quaternion.Euler(new Vector3(0, 0, 90)));
tmp.GetComponent<BulletBehaviour>().Initialize(Vector2.left);
}
}
private void HandleLayers()
{
if (!isGrounded)
{
anim.SetLayerWeight(1, 1);
}
else
{
anim.SetLayerWeight(1, 0);
}
}
}