【问题标题】:How do I fix this moving problem in my 2d game in unity?如何在我的 2d 游戏中统一解决这个移动问题?
【发布时间】:2021-06-24 16:53:48
【问题描述】:

我目前正在尝试学习如何统一制作 2d 游戏。我买了uedemy的课程。显然它不能很好地与移动部分配合使用。我创建了一个这样的动画循环:

显然在一些移动之后,他被卡住并且根本不制作任何动画(除了空闲动画)。

我不太懂这种语言,所以我不知道里面到底发生了什么。这是代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class PlayerCtrl : MonoBehaviour
{


[Tooltip("this is a positive integer which speed up the player movement")]
public int speedBoost;  // set this to 5
public float jumpSpeed; // set this to 600

Rigidbody2D rb;
SpriteRenderer sr;
Animator anim;
bool isJumping;


void Start()
{
    rb = GetComponent<Rigidbody2D>();
    sr = GetComponent<SpriteRenderer>();
    anim = GetComponent<Animator>();
}

void Update()
{
    float playerSpeed = Input.GetAxisRaw("Horizontal"); // value will be 1, -1 or 0
    playerSpeed *= speedBoost;

    if (playerSpeed != 0)
        MoveHorizontal(playerSpeed);
    else
        StopMoving();

    if (Input.GetButtonDown("Jump"))
        Jump();

    ShowFalling();
}

void MoveHorizontal(float playerSpeed)
{
    rb.velocity = new Vector2(playerSpeed, rb.velocity.y);

    if (playerSpeed < 0)
        sr.flipX = true;
    else if (playerSpeed > 0)
        sr.flipX = false;

    if (!isJumping)
        anim.SetInteger("State", 1);
}

void StopMoving()
{
    rb.velocity = new Vector2(0, rb.velocity.y);

    if (!isJumping)
        anim.SetInteger("State", 0);
}

void ShowFalling()
{
    if (rb.velocity.y < 0)
    {
        anim.SetInteger("State", 3);
    }
}

void Jump()
{
    isJumping = true;
    rb.AddForce(new Vector2(0, jumpSpeed)); // simply make the player jump in the y axis or upwards
    anim.SetInteger("State", 2);
}

void OnCollisionEnter2D(Collision2D other)
{
    if (other.gameObject.CompareTag("Ground"))
        isJumping = false;
}
}

如果有人能帮我解决这个问题,我很高兴。提前致谢。

【问题讨论】:

    标签: c# unity3d 2d


    【解决方案1】:

    因此,很遗憾,我认为这里没有足够的信息来对问题做出正确的诊断。此外,您的两个屏幕截图没有帮助,因为它们是完全相同的屏幕截图并且它们正在显示跳跃过渡。所以不能真正从中得到任何东西。

    但您可以尝试的一些事情是make sure that your animations are set to loop。如果它们没有循环播放,它们只会播放一次并且不会继续。但是,这听起来更像是您的移动脚本中出现了问题,并且没有正确更新您的动画状态,因此您需要在那里进行一些调试。

    我会尝试使用Debug.Log() 来确保您的状态设置正确。例如,在您使用anim.SetInteger 的每一行之后添加Debug.Log(anim.GetInteger("State"));

    例子:

    void Jump()
    {
        isJumping = true;
        rb.AddForce(new Vector2(0, jumpSpeed)); // simply make the player jump in the y axis or upwards
        anim.SetInteger("State", 2);
        
        // Debug - add this
        Debug.Log(anim.GetInteger("State"));
    }
    

    您也可以将该行直接添加到Update() 方法中,它会在播放时不断地登录到统一控制台。这种方式只是更干净一点,控制台中的垃圾邮件更少。

    我建议的另一件事是在实际的 Udemy 课程中提出这个问题,向讲师寻求指导。如果 Udemy 课程已过时,这也可能会产生影响,您需要确保使用的是最新的课程(尽管我怀疑是这种情况。)

    如果您可以提供更多信息,也许我们可以为您提供更多帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-29
      • 1970-01-01
      • 1970-01-01
      • 2022-07-26
      • 2022-07-11
      • 2015-03-16
      • 2011-04-12
      • 1970-01-01
      相关资源
      最近更新 更多