# The Coin Flip

Ah the coin flip! Simple easy and fun. The mechanism is a platformer mainstay. You run over a spinning coin (it glitters, it calls you) it pops into the air, and it’s yours!

This is how we do it…

There is a Rigidbody and Collider on both the coin and the player character. You can clearly see the spinning frame of the coin collider in the .gif above.

The collider acts as a trigger which is being listened for by our script which executes the “pop”.

The coin has a spinning script (and also a magnetic feature as a bonus for later).

The player has a couple of behaviours that handles the trigger and action.

Here we have the coin’s Rigidbody and Collider settings:

This is the script we use for spinning:

public class spinCoin : MonoBehaviour {

[Range(0.0F, 500.0F)]
public float speed;

// Update is called once per frame
void Update () {
transform.Rotate(Vector3.up * speed * Time.deltaTime);
}
}

Simple and sweet.

This is the function that that handles the collision and the pop into the air! (It’s part of our character behaviours).

void OnTriggerEnter(Collider otherObj)
{
if (otherObj.name == "Coin(Clone)")
{
coins++;
var coin_txt = coins.ToString();
coinsText.text = "Coins: " + coin_txt;
Rigidbody riji = otherObj.GetComponentInParent<Rigidbody>();
riji.useGravity = true;
riji.isKinematic = false;
riji.AddForce(Vector3.up * 40f,  ForceMode.Impulse);
Destroy(otherObj.gameObject, 0.4f);
}
}

First of all we are incrementing our coin total variables and screen display.

The mesh for the coin is part of a child component so we need to call the Rigidbody attached to the parent object.

We set gravity to true so that it falls back down after adding the force and set isKinematic to false so we can use it’s mass to fall.

After a very short flight we destroy it (0.4 seconds).

As an added bonus here is the other coin behaviour for when a magnet power up is used in the game.

private void OnTriggerEnter(Collider col)
{
colName = col.gameObject.name;
float step = speed * Time.deltaTime; // calculate distance to move

if (colName == "chr_spy2Paintedv2")
{
transform.position = Vector3.MoveTowards(transform.position, col.gameObject.transform.position, step);
}
}

This is when we make the collider really big on the coin. If the player gets in range of the collider then the coin moves like a magnet towards him. Which is kinda fun when there is lots of coins around and you feel like a millionaire just by standing around.