一旦在触发器内按下动作键,就销毁属于预制件的游戏对象

问题描述 投票:0回答:1

所以我正在制作2D平台。我的关卡由多个平台组成,这些平台都是预制件的一部分。我要这样做,以便当我的玩家按下collider2d内部的一个键(在这种情况下为'E')时,玩家上方的平台被破坏,并且平台上的盒子掉落了。

我已经将检测器用于在触发器内按下'E'时起作用,但无法弄清楚如何仅破坏预制件中的单个平台。

任何帮助将不胜感激!

public class SwitchController : MonoBehaviour
{
    public Collider2D switchCollider;
    public Rigidbody2D player;

    void Start()
    {
        switchCollider = GetComponent<Collider2D>();
    }

    private void OnTriggerStay2D(Collider2D col)
    {
        // var player = col.GetComponent<PlayerController>();
        var actionBtn = PlayerController.action;
        if (player)
        {
            Debug.Log("Collided");

            if (Input.GetKeyDown(KeyCode.E))
            {
                actionBtn = true;
                Debug.Log("Action Pressed");
            }

        }
    }
}
c# unity3d
1个回答
0
投票

[如果可能,最简单的解决方案是通过(预制件的)检查器存储平台。然后,您将在需要时销毁游戏对象,例如:

public class SwitchController : MonoBehaviour {

    // ...

    public GameObject targetPlatform;

    private void OnTriggerStay2D(Collider2D col) {
        // ...
        Destroy(targetPlatform); // Destroy the platform.
    }
}

或者,您可以从播放器向上播放光线

public class SwitchController : MonoBehaviour {
    public Collider2D switchCollider;
    public Rigidbody2D player;

    [SerializeField, Tooltip("The layer mask of the platforms.")]
    public LayerMask platformLayerMask;
    void Start() {
        switchCollider = GetComponent<Collider2D>();
    }

    private void OnTriggerStay2D(Collider2D col) {
        var actionBtn = PlayerController.action;

        if (player) {
            if (Input.GetKeyDown(KeyCode.E)) {
                actionBtn = true;
                // Raycast upwards from the player's location.
                // (Raycast will ignore everything but those with the same layermask as 'platformPlayerMask')
                RaycastHit2D hit = Physics2D.Raycast(player.transform.position, Vector2.up, Mathf.Infinity, platformLayerMask);

                if (hit.collider != null) {
                    // Destroy what it hits.
                    Destroy(hit.transform.gameObject);
                }
            }
        }
    }
}

与第一个解决方案相比,此解决方案更具动态性。您只需要在检查器中设置平台的Layers

© www.soinside.com 2019 - 2024. All rights reserved.