c# - 如何在我的 2d 游戏中统一解决这个移动问题?
问题描述
我目前正在尝试学习如何统一制作 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;
}
}
如果有人能帮我解决这个问题,我很高兴。提前致谢。
解决方案
所以,不幸的是,我认为这里没有足够的信息来对问题做出正确的诊断。此外,您的两个屏幕截图没有帮助,因为它们是完全相同的屏幕截图并且它们正在显示跳跃过渡。所以真的不能从中得到任何东西。
但是您可以尝试的一些事情是确保您的动画设置为 loop。如果它们没有循环播放,它们只会播放一次并且不会继续。但是,这听起来更像是您的运动脚本中出现了某些问题,并且没有正确更新您的动画状态,因此您需要在那里进行一些调试。
我会尝试使用 aDebug.Log()
来确保您的 State 设置正确。例如,在您使用anim.SetInteger
add的每一行之后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 课程已过时,那也可能会产生影响,您需要确保使用的是最新的课程(尽管我怀疑是这种情况。)
如果您可以提供更多信息,也许我们可以为您提供更多帮助。
推荐阅读
- jmeter - 如何使用(正文数据-xml/cxml)值在jmeter post请求中参数化/关联?
- mysql - 使用mysql中的存储过程执行sql
- powershell - 无法使用 powershell 获取 Blob
- google-cloud-dataflow - 尝试从 Cloud Dataflow 控制台创建转换文件格式作业时找不到对象错误
- amazon-web-services - Terraform 循环遍历 Swagger Docs 目录并创建 API
- django - /auth/login/ NOT NULL 约束处的 IntegrityError 失败:authtoken_token.user_id
- angular - 密码比较指令@input 在角度模板驱动形式中始终未定义
- node.js - 限制每个用户的会话 - ExpressJS
- c++ - 如何使用 C++ 中的不可复制成员从 initializer_list 创建映射?
- c++ - 将 N 个元素的数组划分为 K 个部分的算法,其中元素之和之间的差异最小