如何使 Physics2D.IgnoreLayerCollision 仅忽略物理硬碰撞而不触发碰撞?

时间:2021-06-24 05:34:27

标签: c# unity3d collision-detection

我刚刚发现了如何忽略冲突,这真的很有帮助。我想要它,因为我想要我的游戏中的一些宝藏既有物理硬碰撞器,也有我的玩家触摸它时的触发器。我不希望我的玩家与宝藏发生物理碰撞,但我确实希望我的宝藏在地面上发生物理碰撞而不是掉下来。

不幸的是,当我使用 Physics2D.IgnoreLayerCollision 时,它也忽略了我在玩家走过宝藏捡起它时使用的触发器碰撞器。我想启用触发碰撞器,禁用物理硬碰撞器。

这是我的代码:

public class colliderTreasureScript : MonoBehaviour
{
    public Rigidbody2D rb;
    public float jumpforce;
    public float speed;
    public LayerMask playerlayer; // 8
    public LayerMask treasurelayer; // 9
    // Start is called before the first frame update
    void Start()
    {
        Physics2D.IgnoreLayerCollision(8, 9, true);
        Physics2D.IgnoreLayerCollision(9, 8, true);
        Physics2D.IgnoreLayerCollision(9, 9,true);
        rb = GetComponent<Rigidbody2D>();
        rb.AddForce(Vector2.up * jumpforce * Time.deltaTime, ForceMode2D.Impulse);
    }

这是另一个捡到宝物的脚本

public class GenericTreasureScript : MonoBehaviour
{
    public float rotatespeed;
    private Player playerscript;
    public int treasurevalue;
    public Transform movetowardsposition;
    public float speed;
    public bool touched;
   // public CircleCollider2D heavycollider;
    // Start is called before the first frame update
    void Start()
    {
        movetowardsposition = GameObject.Find("ScorePositionUpdated").transform;
        touched = false;
        playerscript = FindObjectOfType<Player>();
        //rotatespeed = Random.Range(140, 155.3f);
        speed = Random.Range(18, 22);
    }

    // Update is called once per frame
    void Update()
    {
        if (touched == true)
        {

            transform.position = Vector2.MoveTowards(transform.position, movetowardsposition.position, speed * Time.deltaTime);
        }
        if (Vector2.Distance(transform.position, movetowardsposition.position) < .2f)
        {
            destroy();
        }
}

 private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {


            playerscript.score += treasurevalue;
            touched = true;
            StartCoroutine("destroyBackup");
        }


    }

1 个答案:

答案 0 :(得分:1)

<块引用>

我不希望我的玩家与宝藏发生身体碰撞,但我 确实希望我的宝物在地面上发生物理碰撞而不是掉落 通过

如果你想将物理碰撞器和触发碰撞器分开,仍然在玩家接触时触发但不引起碰撞。

您可以:

  1. 完全移除RigidBody2D,被触发的对象不需要RigidBody2D,只有在您的情况下玩家才会需要并移除物理对撞机
  2. 保留 RigidBody2D 但将 gravityScale 设置为 0 并移除物理碰撞器
  3. 添加另一个额外的层并将物理碰撞器移动到另一个具有该层的父游戏对象上,例如 python test.py \ --path_input_dir gs://somepath \ --dataset somename \ --mp3d_dir gs://somepath \ --file_identifier someid \ --output_file gs://some/other/path \ --num_instructions 1 \ --region us-east1 \ --runner DataflowRunner \ --project someproject-id \ --temp_location gs://someloc ,然后仅禁用该层与玩家之间的碰撞,而不是两个碰撞器都驻留在其上的层

示例 3:

"treasurephysicallayer"

另外设置图层通过。代码是可能的,但在 Physics2D PlayerSettings 中设置它们要容易得多。

您可以通过代码勾选或打开您当前设置的相应碰撞。

Collision Matrix