如何检查 unity2d 平台游戏的地面

How to check ground for unity2d platformer game

我正在尝试制作一个 2d 平台,您可以从侧面看到玩家。我想让他不停地移动,你必须在正确的时间按 space 这样他才不会倒下。现在一切正常,但他没有撞到地面。我希望它就像他 运行 在墙后面,所以我想忽略我制作的某个图层并与下面的框碰撞。到目前为止,我已经尝试过光线投射,观看了多个教程,并进行了盒子碰撞。箱子碰撞起作用了,但要让所有平台都算作坚固,我需要 50 个箱子碰撞器。这是我当前的代码:

public int playerSpeed = 10;
    public int playerJumpPower = 1250;
    public float moveX;
    public float playerYSize = 2;
    public LayerMask mainGround;
    public float playerFallSpeed = 5;

    void Awake(){

    }

    // Update is called once per frame
    void Update()
    {
        RaycastHit2D hit = Physics2D.Raycast(transform.position, new Vector2(10, 0));
        if(hit.distance < 0.7f){
            print("hi");
        }

        Vector3 characterTargetPosition = new Vector3(transform.position.x + playerSpeed, transform.position.y, transform.position.z);
        transform.position = Vector3.Lerp(transform.position, characterTargetPosition, playerSpeed * Time.deltaTime);

        if(Input.GetKeyDown("space")){
            // float playerTargetPosY = transform.position.y + playerJumpPower;
            // Vector3 characterTargetPosition = new Vector3(transform.position.x, playerTargetPosY, transform.position.z);
            // transform.position = Vector3.Lerp(transform.position, characterTargetPosition, playerJumpPower * Time.deltaTime);

            gameObject.GetComponent<Rigidbody2D>().AddForce(Vector2.up * playerJumpPower);
        }
        //PlayerMove();
    }

我的播放器上有一个 rigidBody2D,所以现在他只是从地面掉落,但跳跃确实有效。如果有任何简单的方法可以做到这一点。就像一些脚本、教程或网站一样,我愿意接受它。请帮忙。

你的播放器里有Rigidbody2D吗?会移动的东西通常必须有一个 RigidBody

(很抱歉将此作为答案发布。还不能发表评论)

编辑:

试试这个:

Rigidbody2D rb;

void Awake()
{
    rb = GetComponent<Rigidbody2D>();
}

//Physics usually are done in FixedUpdate to be more constant
public void FixedUpdate(){
    if (Input.GetKeyDown("space"))
    {
        if(!rb.simulated)
            //player can fall
            rb.simulated = true;

        rb.AddForce(Vector2.up * playerJumpPower);
    }
    else
    {
        //third argument is the distance from the center of the object where it will collide
        //therefore you want the distance from the center to the bottom of the sprite
        //which is half of the player height if the center is actually in the center of the sprite
        RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up, playerYSize / 2);

        if (hit.collider)
        {
            //make player stop falling
            rb.simulated = false;
        }
    }
}

如果玩家是唯一会与某物发生碰撞的东西,您可以从玩家不会与之发生碰撞的对象中取出碰撞器。

否则你可以用hit.collider.gameObject.layer检查碰撞对象的层,并决定玩家是否会与该层碰撞

(注意要和层的索引进行比较,如果想通过名称获取索引可以使用LayerMask.NameToLayer(/*layer name*/))

每次你想对 RigidBody 做一些事情(比如 AddForce())时你都必须做 rb.simulated = true

希望对您有所帮助:)