跳跃一次直到角色落地

时间:2018-06-10 21:09:30

标签: c# visual-studio unity3d

我刚刚开始使用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);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您可以使用旗帜来检测玩家何时触地,然后只跳跃玩家正在触地。这可以在truefalse函数中设置为OnCollisionEnterOnCollisionExit

创建一个名为" Ground"的标签。并使游戏对象使用此标记,然后将修改后的代码附加到正在跳跃的玩家。

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来检测楼层。确保将光线投射到地面&#34;只有一层。

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