游戏角色获胜';t双跳c#
本文关键字:双跳 获胜 游戏角色 | 更新日期: 2023-09-27 18:25:26
我正在尝试创建一个统一的2D平台游戏,当我尝试让角色双跳时,它不会起作用。我在想我是否能得到任何帮助。
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float maxSpeed = 3;
public float speed = 50f;
public float jumpPower = 150f;
public bool grounded;
public bool canDoubleJump;
private Rigidbody2D rb2d;
private Animator anim;
void Start ()
{
rb2d = gameObject.GetComponent<Rigidbody2D>();
anim = gameObject.GetComponent<Animator>();
}
void Update ()
{
anim.SetBool("Grounded", grounded);
anim.SetFloat("Speed", Mathf.Abs(rb2d.velocity.x));
if(Input.GetAxis("Horizontal") < -0.1f)
{
transform.localScale = new Vector3(-1, 1, 1);
}
if(Input.GetAxis("Horizontal") > 0.1f)
{
transform.localScale = new Vector3(1, 1, 1);
}
if(Input.GetButton("Jump"))
{
if(grounded)
{
rb2d.AddForce(Vector2.up * jumpPower);
canDoubleJump = true;
}
else
{
if (canDoubleJump)
{
canDoubleJump = false;
rb2d.velocity = new Vector2(rb2d.velocity.x, 0);
rb2d.AddForce(Vector2.up * jumpPower);
}
}
}
}
void FixedUpdate()
{
Vector3 easeVelocity = rb2d.velocity;
easeVelocity.y = rb2d.velocity.y;
easeVelocity.z = 0.0f;
easeVelocity.x *= 0.75f;
float h = Input.GetAxis("Horizontal");
//fake friction / easing x speed
if(grounded)
{
rb2d.velocity = easeVelocity;
}
//moving player
rb2d.AddForce((Vector2.right * speed) * h);
//limiting speed
if(rb2d.velocity.x > maxSpeed)
{
rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
}
if(rb2d.velocity.x < -maxSpeed)
{
rb2d.velocity = new Vector2(-maxSpeed, rb2d.velocity.y);
}
}
}
问题是您正在检查跳转按钮当前是否处于关闭状态按下和释放按钮通常发生在多个帧上(即Update()
在按钮按下期间被调用多次)。
有两种方法可以解决这个问题。
最简单的(可能也是最好的)是进行这种更改:
if(Input.GetButtonDown("Jump"))
GetButtonDown
仅在第一次按下按钮的帧中返回true,在释放并再次按下按钮之前返回false。
另一种是包括第二变量,该第二变量防止第二块的激活直到按钮被释放之后。这不太理想,但显示了GetButtonDown
的幕后情况。
var isButtonDown = false;
Update() {
if(Input.GetButton("Jump"))
{
if(grounded)
{
rb2d.AddForce(Vector2.up * jumpPower);
canDoubleJump = true;
isButtonDown = true;
}
else if(!isButtonDown)
{
if (canDoubleJump)
{
canDoubleJump = false;
rb2d.velocity = new Vector2(rb2d.velocity.x, 0);
rb2d.AddForce(Vector2.up * jumpPower);
}
}
}
else {
isButtonDown = false;
}
}
请注意,这并没有解决双跳能力通常包括的"从平台上摔下来跳一次"问题。我将把它留给读者练习。