[英]Trying to make my 2D character double jump - it's not working and I don't know why?
我正在制作2D平台游戏。 到目前为止,这是我的代码。 角色仅在接触地面时才跳,但两次跳的代码不起作用。 任何帮助表示赞赏。 我是脚本新手,我不明白自己做错了什么?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
public float speed = 12f, jumpHeight = 30f;
Rigidbody2D playerBody;
Transform playerTrans, tagGround;
bool isGrounded = false;
public LayerMask playerMask;
public float maxJumps = 2;
public float jumpsLeft = 2;
// Use this for initialization
void Start ()
{
playerBody = this.GetComponent<Rigidbody2D>();
playerTrans = this.transform;
tagGround = GameObject.Find(this.name + "/tag_Ground").transform;
}
// Update is called once per frame
public void FixedUpdate ()
{
isGrounded = Physics2D.Linecast(playerTrans.position, tagGround.position, playerMask);
Move();
Jump();
DoubleJump();
}
private void Move()
{
float move = Input.GetAxisRaw("Horizontal") * speed;
playerBody.velocity = new Vector2(move, playerBody.velocity.y);
}
private void Jump()
{
if (isGrounded)
{
if (Input.GetButtonDown("Jump"))
{
playerBody.velocity = new Vector2(playerBody.velocity.x, jumpHeight);
}
}
}
private void DoubleJump()
{
if (Input.GetButtonDown("Jump") && jumpsLeft > 0)
{
Jump();
jumpsLeft--;
}
if (isGrounded)
{
jumpsLeft = maxJumps;
}
}
}
尝试用DoubleJump方法的代码替换您的Jump方法代码,并在应用跳转之前删除对IsGrounded的检查。 否则,您的角色必须每次都在地面上。 然后,删除不再需要的DoubleJump方法。 如果您稍后在游戏中将DoubleJump用作附加技能,则随着玩家获得技能而增加maxJumps。 最初将其设置为1,这样它们每次都必须接地。
private void Jump() {
if (isGrounded) {
jumpsLeft = maxJumps;
}
if (Input.GetButtonDown("Jump") && jumpsLeft > 0) {
playerBody.velocity = new Vector2(playerBody.velocity.x, jumpHeight);
jumpsLeft--;
}
}
您的代码没有多大意义。 您应该使用一种方法来处理跳跃,并执行以下操作:
private void HandleJump()
{
if(isGrounded) {
jumpsLeft = maxJumps;
}
if(Input.GetButtonDown("Jump") && jumpsLeft > 0) {
playerBody.velocity = new Vector2(playerBody.velocity.x, jumpHeight);
jumpsLeft--;
}
}
这样,您可以进行三级跳跃,也可以进行任意多次跳跃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.