所以基本上,经过几个小时的折磨尝试为简单的平台游戏创建基本的动作脚本我成功了,但并不完全。方形角色能够四处移动并且跳得很好,但有时它不会跳跃,通常是在短距离移动时,或者很少站在原地并试图跳跃。我无法弄清楚如何解决这个问题。这是完整的脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
private Rigidbody2D rgdb2;
public float movementSpeed;
public float jumpHeight;
private bool isJumping = false;
// Use this for initialization
void Start ()
{
rgdb2 = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis("Horizontal");
HandleMovement(moveHorizontal);
if (Input.GetKeyDown(KeyCode.Space) && isJumping == false)//by typing Space player jumps, cant double-jump
{
rgdb2.AddForce(new Vector2(rgdb2.velocity.x, 1 * jumpHeight), ForceMode2D.Impulse);
isJumping = true;
Debug.Log("jumped");
}
}
private void HandleMovement(float moveHorizontal)//applying player horizontal controls and customing player's speed by movementSpeed variable
{
rgdb2.velocity = new Vector2(moveHorizontal * movementSpeed, rgdb2.velocity.y);
}
private void OnCollisionEnter2D(Collision2D coll)
{
if (coll.transform.tag == "Platform") //if player is touching object with Platform tag, he can jump
{
Debug.Log("on ground bitch");
isJumping = false;
}
}
}
它可能不那么重要,但我想尽可能地打磨这个游戏,即使我不需要,因为它基本上是我在Unity3d用C#制作的第一个游戏。
需要记住的一件重要事情是:Unity3D Engine的输入仅在引擎为您的GameObjects调用Update()
方法时更新。
这意味着您不应该在FixedUpdate()
方法中读取任何类型的输入。在GetKeyDown()期间,不应调用FixedUpdate()
和Input类中读取键盘/鼠标/轴按钮/值的其他方法,因为它们的返回值不可靠。
因此,当用户按下跳转键时,可能导致跳转实现失败的原因是你在GetKeyDown()中调用的FixedUpdate()
方法返回不一致/无效(false
)结果。
修复此问题非常简单。我建议你保留一个布尔变量来跟踪跳转键是否被按下,并在Update()
期间更新其值。这应该可以解决您的问题。
bool jumpKeyPressed;
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
jumpKeyPressed = true;
else if (Input.GetKeyUp(KeyCode.Space))
jumpKeyPressed = false;
}
private void FixedUpdate()
{
/* Update "moveHorizontal", call HandleMovement(...) here, as you've already done. */
if (jumpKeyPressed && isJumping == false)
{
// IMPORTANT: this prevents the "jump force" from being applied multiple times, while the user holds the Space key
jumpKeyPressed = false;
/* Remaining jumping logic goes here (AddForce, set "isJumping", etc) */
}
}
这是因为你的跳跃逻辑在FixedUpdate()里面
当您使用GetKeyDown注册输入时,请确保使用Update,因为如果您使用FixedUpdate按键,它可能会或可能不会在该帧期间运行,请使用Update进行测试。
你已经在评论中有了Update如何工作,它根据Unity documentation被称为每个帧但是FixedUpdate:每个固定的帧率帧调用此函数
void Update ()
{
float moveHorizontal = Input.GetAxis("Horizontal");
HandleMovement(moveHorizontal);
if (Input.GetKeyDown(KeyCode.Space) && isJumping == false)//by typing Space player jumps, cant double-jump
{
rgdb2.AddForce(new Vector2(rgdb2.velocity.x, 1 * jumpHeight), ForceMode2D.Impulse);
isJumping = true;
Debug.Log("jumped");
}
}