简体   繁体   English

我的角色不会攀登,只会跌落在统一2D中

[英]my character wont climb and just falls in unity 2d

Im very new to Unity and C# I have been trying to make my character climb on ladders for hours and tried 20+ diffrent scripts but nothing is working.I am putting the script on the collider around the ladder(the ladder is part of the tiles)i even added a spirit behind the tiles where the ladders and put the collider around them but nothing the character just falls(i have put the collider as a trigger)again i am new this was a code i found that a lot of people liked but it seemed not to work for me here is the ladder code: 对于Unity和C#来说,我很陌生,我一直试图让我的角色爬上梯子几个小时,并尝试了20多种不同的脚本,但没有任何效果。我将脚本放在梯子周围的对撞机上(梯子是瓷砖的一部分) )我什至在瓷砖后面的梯子上添加了一种精神,并在其周围放置了对撞机,但角色没有掉下来(我已将对撞机作为触发器)再次我是新的,这是一个代码,我发现很多人喜欢但是这似乎对我不起作用,这是阶梯代码:

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

public class Ladder : MonoBehaviour
{

    GameObject playerOBJ;
    bool canClimb = false;
    float speed = 1;

    void OnCollisionEnter(Collision coll)
    {
        if (coll.gameObject.tag == "Player")
        {
            canClimb = true;
            playerOBJ = coll.gameObject;
        }
    }

    void OnCollisionExit(Collision coll2)
    {
        if (coll2.gameObject.tag == "Player")
        {
            canClimb = false;
            playerOBJ = null;
        }
    }
    void Update()
    {
        if (canClimb)
        {
            if (Input.GetKey(KeyCode.W))
            {
                playerOBJ.transform.Translate(new Vector3(0, 1, 0) * Time.deltaTime * speed);
            }
            if (Input.GetKey(KeyCode.S))
            {
                playerOBJ.transform.Translate(new Vector3(0, -1, 0) * Time.deltaTime * speed);
            }
        }
    }
}'

You need to disable the gravity on your character rigidbody while climbing otherwise the gravity will always take your character down. 您需要在攀爬时禁用角色刚体上的重力,否则重力将始终使您的角色坠落。

You can access your character rigidbody like this: 您可以像这样访问角色刚体:

playerRB = playerOBJ.GetComponent<Rigidbody2D>();

you can change the gravity to 0: 您可以将引力更改为0:

playerRB.gravityScale = 0; and back to 1 when you need to. 然后在需要时返回1。

For instance disable the gravity anytime your character hit the ladder collider and enable the gravity when you press "A" or "D" to make your character fall from the ladder. 例如,当您的角色碰到梯子对撞机时就禁用重力,而当您按下“ A”或“ D”使您的角色从梯子上掉下来时启用重力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM