【问题标题】:Jump once only until character lands只跳一次,直到角色落地
【发布时间】:2018-06-10 21:09:30
【问题描述】:

我刚开始使用 Unity 正在尝试制作一个简单的 3D 平台游戏,在我开始之前,我需要先让运动下降。当玩家跳跃时,我的问题就出现了。当他们跳跃时,他们可以随心所欲地在空中跳跃。我希望它只跳一次。有人可以帮忙吗?

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

public class Playermovement : MonoBehaviour 
{
    public Rigidbody rb;

    void Start ()   
    }

        void Update()
        {
            bool player_jump = Input.GetButtonDown("DefaultJump");
            if (player_jump)
            {
                rb.AddForce(Vector3.up * 365f);
            }
        }
    }
}

【问题讨论】:

    标签: c# visual-studio unity3d


    【解决方案1】:

    您可以使用标志来检测玩家何时触地,然后仅在玩家触地时才跳跃。这可以在OnCollisionEnterOnCollisionExit 函数中设置为truefalse

    创建一个名为“Ground”的标签并让 GameObjects 使用此标签,然后将以下修改后的代码附加到正在跳跃的玩家身上。

    private Rigidbody rb;
    bool isGrounded = true;
    public float jumpForce = 20f;
    
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }
    
    private void Update()
    {
        bool player_jump = Input.GetButtonDown("DefaultJump");
    
        if (player_jump && isGrounded)
        {
            rb.AddForce(Vector3.up * jumpForce);
        }
    }
    
    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Ground"))
        {
            isGrounded = true;
        }
    }
    
    
    void OnCollisionExit(Collision collision)
    {
        if (collision.gameObject.CompareTag("Ground"))
        {
            isGrounded = false;
        }
    }
    

    有时,使用OnCollisionEnterOnCollisionExit 可能不够快。这很少见,但可能。如果遇到这种情况,请使用带有Physics.Raycast 的 Raycast 来检测地板。确保只将光线投射到“地面”层。

    private Rigidbody rb;
    public float jumpForce = 20f;
    
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }
    
    private void Update()
    {
        bool player_jump = Input.GetButtonDown("DefaultJump");
    
        if (player_jump && IsGrounded())
        {
            rb.AddForce(Vector3.up * jumpForce);
        }
    }
    
    bool IsGrounded()
    {
        RaycastHit hit;
        float raycastDistance = 10;
        //Raycast to to the floor objects only
        int mask = 1 << LayerMask.NameToLayer("Ground");
    
        //Raycast downwards
        if (Physics.Raycast(transform.position, Vector3.down, out hit,
            raycastDistance, mask))
        {
            return true;
        }
        return false;
    }
    

    【讨论】:

    • 我想通了!起初我不知道如何添加标签,但我只是查看了设置。非常感谢,这真的很有帮助!。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多