Scripting the Coin Box Component

The Component we’re about to script will swap between the active and disabled versions of the coin box Prefabs when the player strikes the box from below. Open the CoinBox script and fill it out as shown in Listing 8.4.

Listing 8.4 The CoinBox Script

public class CoinBox : MonoBehaviour{  public GameObject poppedStatePrefab;  void OnTriggerEnter2D(Collider2D collider)  {    Vector3 heading = this.transform.position - collider.gameObject.transform.position;    float distance = heading.magnitude;    Vector3 direction = heading / distance;    if((direction.x < 0.1 && direction.x > -1.1)      && (direction.y < 1.1 && direction.y > 0.4)      && collider.tag == "Player")    {      CoinPop(); ...

Get Learning 2D Game Development with Unity®: A Hands-On Guide to Game Creation now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.