gpt4 book ai didi

c# - "isGrounded"在 Unity 中初始跳转后变量不会更改为 false

转载 作者:行者123 更新时间:2023-12-04 10:22:17 28 4
gpt4 key购买 nike

概述

使用 Unity2D 2019.3.5,我正在使用 C# 制作平台游戏。我实现了光线转换来检测我的玩家何时接触地面并试图让它只让玩家只能跳跃一次。

问题

虽然我认为我将我的角色编程为跳跃一次,但在第一次跳跃后,Unity 引擎仍然对我的“isGrounded”变量显示一个复选标记,并且仅在第二次跳跃后才变为假(未选中)然后才落地。

我的代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player_Controller : MonoBehaviour
{

public int playerSpeed = 10;
public int playerJumpPower = 1250;
private float moveX;
public bool isGrounded;
public float distanceToBottomOfPlayer = .7f;

// Update is called once per frame
void Update()
{
PlayerMove();
PlayerRaycast();
}

void PlayerMove()
{
// CONTROLS
moveX = Input.GetAxis("Horizontal");
if (Input.GetButtonDown("Jump") && isGrounded == true)
{
Jump();
}

// ANIMATIONS

// PLAYER DIRECTION
if (moveX < 0.0f)
{
GetComponent<SpriteRenderer>().flipX = true;
}
else if (moveX > 0.0f)
{
GetComponent<SpriteRenderer>().flipX = false;
}

// PHYSICS
gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(moveX * playerSpeed,
gameObject.GetComponent<Rigidbody2D>().velocity.y);
}

void Jump()
{
GetComponent<Rigidbody2D>().AddForce(Vector2.up * playerJumpPower);
isGrounded = false;
}

void PlayerRaycast()
{
// Ray Down
RaycastHit2D rayDown = Physics2D.Raycast(transform.position, Vector2.down);

if (rayDown.collider != null && rayDown.distance < distanceToBottomOfPlayer &&
rayDown.collider.tag == "ground")
{
isGrounded = true;
}
}
}

额外信息

我确实必须在 Edit > Project Settings > Physics 2D > Queries Start In Colliders 中更改 Unity 设置。我必须关闭此设置(取消选中)才能让我的播放器使用我上面编写的代码跳转。我知道还有其他方法可以让我的玩家跳跃,但是,这似乎是最有效的,同时保持代码的可读性。

已尝试的解决方案

我认为问题在于我有一个不知道如何解决的光线转换问题。我查看了其他 Stack Overflow 帖子,包括在写完这篇帖子后推荐的帖子,但没有一个适用于我的问题。

最后说明

正如我之前所说,我知道还有其他方法可以让我的玩家只跳一次使用不同的代码,但是,出于我自己的学习目的和将来的引用,我想坚持使用此代码。

最佳答案

因为你不能确定isGroundedfalse当您调用 Jump() .
我认为问题出在那儿。
尽量不要设置isGrounded调用 Jump() 时的标志.设置isGrounded纯粹是PlayerRaycast()的工作。

    void Update()
{
// Raycast before moving
PlayerRaycast();
PlayerMove();
}

void PlayerRaycast()
{
// Ray Down
RaycastHit2D rayDown = Physics2D.Raycast(transform.position, Vector2.down);

if (rayDown.collider != null && rayDown.collider.tag == "ground")
{
if( rayDown.distance < distanceToBottomOfPlayer )
{
isGrounded = true;
}
else
{
isGrounded = false;
}
}
}

void Jump()
{
GetComponent<Rigidbody2D>().AddForce(Vector2.up * playerJumpPower);
//isGrounded = false;
}

关于c# - "isGrounded"在 Unity 中初始跳转后变量不会更改为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60804308/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com