2
\$\begingroup\$

I'm creating a 2d game and I want to make it so that tiles are destructible whenever a projectile collides with a tile, the problem is I don't know how to get the tile that the projectile is colliding with, I would like to make it so that it area of damage.

However for now I want to make it so that once the projectile reaches the ground it destroys the tile it's sitting on I've made a collider2d to help me with that but I still have no idea how to get the tile that's the projectile is sitting on.

IEnumerator OnCollisionEnter2D(Collision2D x)
    {
    Vector2 hit = gameObject.transform.position;
    Debug.Log("y" + hit.y);
    hit.y =- 3; // What y should i put here in order to make sure its the same as the tile the projectile is sitting on
        if (x.gameObject.tag != "Player")
        { 
        Collider2D[] collidedwith = Physics2D.OverlapCircleAll(this.gameObject.transform.position, radius);
        tilemap.SetTile(tilemap.WorldToCell(hit), null);  
    }

A screenshot for better explanation (I would like to get rid of the blue tile):image

\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

Have you considered using the contactpoint2d? It gives you information about the contact point where the collision occurred. Here is a demo code grabbed from 2D tech demo on tilemap.

void OnCollisionEnter2D(Collision2D collision)
{
    Vector3 hitPosition = Vector3.zero;
    foreach (ContactPoint2D hit in collision.contacts)
    {
       hitPosition.x = hit.point.x - 0.01f * hit.normal.x;
       hitPosition.y = hit.point.y - 0.01f * hit.normal.y;
       tilemap.SetTile(tilemap.WorldToCell(hitPosition), null);
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ thanks i was able to come up with a solution using what u posted i had to add a few lines in and it works perfectly do you have any idea how i could implement this so that its circular (for example destroy the projectile destroys 3 blocks around it) \$\endgroup\$
    – flex_
    Jun 10, 2019 at 1:17
2
\$\begingroup\$

ok so i solved it by using shuvro's code along with some stuff added in

 Tilemap tilemap = GetComponent<Tilemap>();
        Vector3 hitPosition = Vector3.zero;
        foreach (ContactPoint2D hit in collision.contacts)
        {
            Debug.Log(hit.point);
            hitPosition.x = hit.point.x - 0.1f;
            hitPosition.y = hit.point.y - 0.1f ;
            Vector3Int cell = new Vector3Int((int)hitPosition.x, (int)hitPosition.y, 0);

            tilemap.SetTile(tilemap.WorldToCell(hitPosition), null);
        }
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .