【发布时间】:2021-04-11 03:41:42
【问题描述】:
这几天我的跳跃动画一直有一些问题,我想知道如何制作它,所以当我按下“SPACE”键时,它会播放我的跳跃动画。我的动画师中已经有一个名为 isJumping 的布尔函数,只是我不知道如何在脚本中调用它来播放我的跳跃动画。我尝试了很多教程来找出我的答案,但其中大多数并没有很好地解释如何做到这一点。我已经设置了我的行走动画,只是我知道需要知道如何制作我的跳跃动画。
Image of my animator
enter image description here
到目前为止我的代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PM : MonoBehaviour
{
public float moveSpeed;
public float jumpHeight;
Rigidbody2D rb;
BoxCollider2D boxColliderPlayer;
int layerMaskGround;
float heightTestPlayer;
public Animator animator;
void Start()
{
rb = GetComponent<Rigidbody2D>();
// Get the player's collider so we can calculate the height of the character.
boxColliderPlayer = GetComponent<BoxCollider2D>();
// We do the height test from the center of the player, so we should only check
// halft the height of the player + some extra to ignore rounding off errors.
heightTestPlayer = boxColliderPlayer.bounds.extents.y + 0.05f;
// We are only interested to get colliders on the ground layer. If we would
// like to jump ontop of enemies we should add their layer too (which then of
// course can't be on the same layer as the player).
layerMaskGround = LayerMask.GetMask("Ground");
}
void Update()
{
float moveDir = Input.GetAxis("Horizontal") * moveSpeed;
rb.velocity = new Vector2(moveDir, rb.velocity.y);
// Your jump code:
if (Input.GetKeyDown(KeyCode.Space) && IsGrounded() )
{
rb.velocity = new Vector2(rb.velocity.x, jumpHeight);
}
animator.SetFloat("Speed",Mathf.Abs(moveDir));
}
/// <summary>
/// Simple check to see if our character is no the ground.
/// </summary>
/// <returns>Returns <c>true</c> if the character is grounded.</returns>
private bool IsGrounded()
{
// Note that we only check for colliders on the Ground layer (we don't want to hit ourself).
RaycastHit2D hit = Physics2D.Raycast(boxColliderPlayer.bounds.center, Vector2.down, heightTestPlayer, layerMaskGround);
bool isGrounded = hit.collider != null;
// It is soo easy to make misstakes so do a lot of Debug.DrawRay calls when working with colliders...
Debug.DrawRay(boxColliderPlayer.bounds.center, Vector2.down * heightTestPlayer, isGrounded ? Color.green : Color.red, 0.5f);
return isGrounded;
}
}
【问题讨论】: