2D Physics: Fun with Effectors

Checked with version: 5

-

Difficulty: Beginner

In this live training session we're going to show you how to use 2D Physics Effectors to create areas of your scene which can add physics forces to objects or change their physics behavior. The Effectors we'll look at include Platform Effector 2D, Surface Effector 2D, Area Effector 2D and Point Effector 2D. We'll do this in the context of a platformer style game.

2D Physics: Fun with Effectors

Beginner 2D Game Creation

CoinSprayer

Code snippet

using UnityEngine;
using System.Collections;

public class CoinSprayer : MonoBehaviour {

    public int numCoins = 10;
    public GameObject coinPrefab;
    public float offSetRange = 1.5f;

    // Use this for initialization
    void Start () {
        SpawnCoins();
    
    }
    
    void SpawnCoins()
    {
        for (int i = 0; i < numCoins; i++)
        {
            Vector2 spawnOffset = new Vector2 (Random.Range(-offSetRange, offSetRange), Random.Range(-offSetRange, offSetRange));
            Instantiate(coinPrefab, (Vector2)transform.position + spawnOffset, Quaternion.identity);
        }
    }
}

DropCoins

Code snippet

using UnityEngine;
using System.Collections;

public class DropCoins : MonoBehaviour {

    public GameObject coinSprayerPf;
    bool gotHit;

    void OnCollisionEnter2D (Collision2D col)
    {
        if (col.gameObject.CompareTag("Enemy") && !gotHit)
        {
            gotHit = true;
            Instantiate(coinSprayerPf, transform.position, Quaternion.identity);
        }
    }
}

Related tutorials