【发布时间】:2019-02-02 05:50:40
【问题描述】:
我刚刚开始学习如何在 Unity 中制作一个简单的 2D 平台游戏,并且我观看了 Blackthornprod 2D Platformer movement video 以学习如何让角色移动和跳跃。到目前为止,我能够理解大部分视频,但是,我在跳跃部分遇到了一些问题。
现在,据我在他的视频中了解,要让角色跳跃,我需要检测角色是否接触地面。为此,我需要在玩家脚下创建一个小圆圈,看看它是否与地面重叠,like this
所以,这里是代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float JumpForce; // jumping force
private bool isGrounded; //if the player is touching the ground
public Transform GroundCheck; //object that contains the position of the
//"circle"
public LayerMask GroundLayer; //the layer that the "circle" collide with
public float radius; //radius of the circle
public float BaseNumOfJumps; //maximum number of jumps
private float NumOfJumps; //current number of jumps
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
NumOfJumps = BaseNumOfJumps;
}
void FixedUpdate()
{
//check the collision between the "circle" and the ground
isGrounded = Physics2D.OverlapCircle(GroundCheck.position,
radius,GroundLayer);
//here is the horizontal movement update part, but they are
//irrelevant so I cut them off
}
void Update()
{
//if the player touches the ground, reset the number of jumps
if (isGrounded)
{
NumOfJumps = BaseNumOfJumps;
}
//when jumping, decrease the number of jumps
if (Input.GetKeyDown(KeyCode.UpArrow) && NumOfJumps > 0)
{
rb.velocity = Vector2.up * JumpForce;
NumOfJumps--;
}
}
}
问题就从这里开始,实际的最大跳跃次数总是高于我输入的值。例如,如果我设置 BaseNumOfJumps = 2,那么我可以跳 3 次而不是 2 次,类似地,如果 BaseNumOfJumps = 1 则我可以跳 2 次,依此类推。
过了一会儿,我发现因为圆圈的大小总是比实际玩家的脚大一点,所以当我跳跃时,玩家的脚在空中的那一刻,但是圆圈仍然与地面重叠,这会重置当前的跳跃次数(在我的代码中也称为 NumOfJumps),并使我的角色能够比在 BaseNumOfJumps 中输入的次数多跳一次。 不知道是真是假,but here was what I imagined。 This comment under the video also described the same problem.
虽然 Blackthornprod 已经将这些值称为“额外跳跃”,所以如果我在该值中输入“1”,我会跳两次,“2”我会跳 3 次,等等。我在制作时遇到了一些困难跳跃次数一致。如果我的角色只是滑离地面而不跳like this怎么办?圆圈不会与地面发生碰撞,我将能够跳出我在 BaseNumOfJumps 中输入的确切跳跃次数,简而言之:
如果我输入的最大跳跃次数为 2,我将能够(再次重申,这只是我的猜测,所以我可能错了):
这当然会造成一些不一致。我已经搜索过其他关于跳跃和碰撞的教程,但其中大多数要么使用其他形式的检查碰撞(如 OnCollisionStay、OnCollisionEnter),要么使用我使用的相同方法但没有深入解释它(所以基本上它们是相同的就像在 Blackthornprod 的视频中一样)
那么我该如何解决这个问题,如何改变“圆”的半径,使其在玩家跳跃时脚离开地面的同一时刻离开地面?或者我应该像之前提到的那样使用其他形式的碰撞检查,如果是,它们有什么区别,哪种最有效?
这是我在这里的第一个问题,由于我不熟悉英语,我知道这有点长且令人困惑,但如果有人能提供帮助,我将不胜感激。
【问题讨论】: