Rud*_*der 3 c# unity-game-engine visual-studio
我刚刚开始使用 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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用标志来检测玩家何时接触地面,然后仅在玩家接触地板时跳跃。这可以在和函数中设置为true和。falseOnCollisionEnterOnCollisionExit
创建一个名为“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;
}
}
Run Code Online (Sandbox Code Playgroud)
有时,使用OnCollisionEnterandOnCollisionExit可能不够快。这种情况很少见,但也是可能的。如果遇到这种情况,请使用 Raycast 来Physics.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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3378 次 |
| 最近记录: |