I just discovered how to ignore collisions and it's really helpful. I want it because I want some treasure in my game to both have a physical hard collider, and a trigger for when my player touches it. I don't want my player to collide physically with the treasure, but I do want my treasure to collide physically on the ground and not fall through.
Unfortunately when I used Physics2D.IgnoreLayerCollision it also ignores my Trigger collider that I use for when my player walks over the treasure to pick it up. I want the trigger collider to be enabled, and the physical hard collider to be disabled.
Here's my code:
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);
}
Here's another script for picking up the treasure
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");
}
}
