繁体   English   中英

玩家跳跃 animation 不在 unity2d 中播放

[英]Player jumping animation not playing in unity2d

几天前我的 Jump animation 遇到了一些问题,我想知道如何做到这一点,所以当我按下“SPACE”键时,它将播放我的 Jump animation。 我已经有一个布尔 function 在我的动画师中称为 isJumping,只是我不知道如何在脚本中调用它来播放我的跳跃 animation。 我尝试了很多教程来找出我的答案,但其中大多数并没有很好地解释如何做到这一点。 我已经设置了我的行走 animation 只是我知道需要知道如何做我的跳跃动画。

Image of my animator图像在此处输入图像描述

到目前为止我的代码

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

我不知道您的 animation 树是如何设置的。 为此,请从其他状态转换,如果 isJump 设置为 true,那么它将从 state 转换为跳跃(当然跳跃除外),然后退出您的跳跃回到入口或空闲或其他状态state 在跳跃结束时最有意义。 如果您发布树的图像,我可以在需要时为您提供帮助。

使用转换和单独的 state 设置并使用 bool 触发转换,使 animation 播放所需的唯一代码应该是:

animator.SetBool("isJumping", true);

一旦您在 isGrounded function 中检测到播放器再次接地,请使用相同的代码段但传入 false 以停止跳转 animation。

animator.SetBool("isJumping", false);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM