这是我的跳转代码,它在 void Update 中更新
void Jump()
{
if(isgrounded == true)
{
amountofjumps = jumps;
}
if(Input.GetKeyDown(KeyCode.UpArrow) && amountofjumps > 0)
{
rb2d.velocity = Vector2.up * jump * Time.deltaTime;
amountofjumps--;
}
else if(Input.GetKeyDown(KeyCode.UpArrow) && amountofjumps == 0 && isgrounded == true)
{
rb2d.velocity = Vector2.up * jump * Time.deltaTime;
}
}
这是我用于跳转代码的变量
bool isgrounded;
public float groundcheckradius;
public LayerMask whatisground;
public float jump;
private int amountofjumps;
public int jumps;
这是我检测地面的方法
void checkforground()
{
isgrounded = Physics2D.Raycast(transform.position,Vector2.down, groundcheckradius,whatisground);
}
void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawLine(transform.position, transform.position + Vector3.down * groundcheckradius);
}
提前致谢
答案 0 :(得分:0)
Velocity 通常用于移动对象 try rigidbody2d.AddForce()
。
void Jump()
{
if (isgrounded == true)
{
amountofjumps = jumps;
}
if (Input.GetKeyDown(KeyCode.UpArrow) && amountofjumps > 0 && isgrounded == true)
{
rb2d.AddForce(transform.up * jump, ForceMode2D.Impulse);
amountofjumps--;
}
}
答案 1 :(得分:0)
首先,设置 Time.deltaTime
时 velocity
没有意义。 velocity
已经与帧速率无关,因此当您将速度乘以 Time.deltaTime
(对于 60 fps 大约为 0.017)时,它会变得非常小/慢。
其次,当前您会覆盖整个速度,因此如果您的玩家向前移动,它将完全停止 X 轴上的任何移动。
最后,当您接地时,您希望总是能够跳跃……不仅是在 amountofjumps == 0
的情况下,永远是这种情况因为就在您将其设置为 amountofjumps = jumps;
之前!从地面跳跃时,您根本不想检查 amountofjumps
!
您可能更愿意使用例如
// get the current velocoty of the rigidbody
var velocity = rb2d.velocity;
// Only overwrite the Y velocity with the jump
velocity.y = jump;
// re-assign the changed vector to the rgidbody
rb2d.velocity = velocity;
然后我会将逻辑更改为例如
private void Jump()
{
if(isgrounded)
{
amountofjumps = jumps;
// when you are grounded you can always jump!
// Not only when the amountofjumps == 0
// actually when you are grounded the amountofjumps shouldn't matter at all
if(Input.GetKeyDown(KeyCode.UpArrow))
{
DoJump();
}
}
// As before while not grounded the amountofjumps is taken into account
else if(amountofjumps > 0)
{
if(Input.GetKeyDown(KeyCode.UpArrow))
{
DoJump();
}
}
}
private void DoJump()
{
// get the current velocoty of the rigidbody
var velocity = rb2d.velocity;
// Only overwrite the Y velocity with the jump
velocity.y = jump;
// re-assign the changed vector to the rgidbody
rb2d.velocity = velocity;
// Always reduce the amount of jumps also when jumping from the ground
amountofjumps--;
}