“ isGrounded”变量在Unity中进行初始跳转后不会变为false

问题描述 投票:1回答:1

概述

使用Unity2D 2019.3.5,我正在使用C#制作平台游戏。我实施了raycast来检测我的播放器何时接触地面,并尝试使其仅接地,因此播放器只能跳跃一次。

问题

尽管我以为我将角色编程为跳一次,但在第一次跳后,Unity引擎仍对我的“ isGrounded”变量显示一个对号,并且在第二次跳到地面之前仅变为false(未经检查)。 >

我的代码

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;
        }
    }
}

额外信息

我确实必须在“编辑”>“项目设置”>“ Physics 2D”>“在碰撞器中开始查询”中更改Unity设置。我必须关闭(取消选中)此设置,才能使播放器使用上面编写的代码跳转。我知道还有其他方法可以使我的播放器跳转,但是,这在保持代码可读性的同时,似乎是最有效的。

已尝试的解决方案

我相信问题是我有一个射线广播问题,不知道如何解决。我查看了其他Stack Overflow帖子,包括在撰写本psot之后推荐的帖子,但没有一个适用于我的问题。

最后注释

[正如我之前说过的,我知道还有其他方法可以使我的播放器使用不同的代码仅跳跃一次,但是,我想坚持使用此代码,以供我自己学习,以备将来参考。

使用Unity2D 2019.3.5进行概述,我正在使用C#制作平台游戏。我实施了raycast来检测我的播放器何时触地,并试图使其进入地面,以便播放器可以跳跃...

c# unity3d raycasting
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.