[英]Why is the IsGrounded function True when I press space, and not when im on the ground
我是 Unity 的新手,我正在努力做到這一點,以便玩家在他們已經使用IsGrounded跳躍時無法跳躍,這應該檢查他們是否在地面上,但如果按下空格鍵則IsGrounded 為真。 這可能是 Unity 本身的問題,但我不確定。 感謝: 代碼:
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
float xInput, yInput;
[SerializeField] private LayerMask lm;
private Rigidbody2D rb;
private BoxCollider2D bc;
// Start is called before the first frame update
void Start()
{
}
private void Awake()
{
rb = transform.GetComponent<Rigidbody2D>();
bc = transform.GetComponent<BoxCollider2D>();
}
// Update is called once per frame
void Update()
{
if (IsGrounded() && Input.GetKeyDown(KeyCode.Space))
{
float jumpVelocity = 25f;
rb.velocity = Vector2.up * jumpVelocity;
Debug.Log("IsGrounded");
}
xInput = Input.GetAxis("Horizontal");
transform.Translate(xInput * moveSpeed, 0, 0);
PlatformerMove();
}
void PlatformerMove()
{
rb.velocity = new Vector2(moveSpeed * xInput, rb.velocity.y);
}
private bool IsGrounded()
{
RaycastHit2D rc = Physics2D.BoxCast(bc.bounds.center, bc.bounds.size, 0f, Vector2.down * .1f, lm);
return rc.collider != null;
}
}```
您正在使用
Physics2D.BoxCast(bc.bounds.center, bc.bounds.size, 0f, Vector2.down * .1f, lm);
現在,如果您查看Physics2D.BoxCast
的參數
public static RaycastHit2D BoxCast( Vector2 origin, Vector2 size, float angle, Vector2 direction, float distance = Mathf.Infinity, int layerMask = Physics2D.AllLayers, float minDepth = -Mathf.Infinity, float maxDepth = Mathf.Infinity );
你正在傳遞
origin
= bc.bounds.center
size
= bc.bounds.size
direction
= Vector2.down
(幅度與距離無關!)distance
= lm
(我想你現在注意到了這個問題)=>我想這是一個圖層蒙版 -> 一些相當大的 integer -> 你射得很遠 -> 可能總是擊中某物layerMask
= Physics2D.AllLayers
一般來說,因為它是一個 Box cast ,這意味着您正在將一個盒子發射到太空中並檢查它是否在途中擊中了某些東西。
如果這是有意的,你寧願通過
RaycastHit2D rc = Physics2D.BoxCast(bc.bounds.center, bc.bounds.size, 0f, Vector2.down, 0.1f, lm);
否則我想你寧願使用Physics2D.OverlapBox
而不是檢查固定位置/區域中的重疊而不是在任何地方拍攝
RaycastHit2D rc = Physics2D.OverlapBox(bc.bounds.center, bc.bounds.size, 0f, lm);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.