Techshop

Unity Tutorial 28 - Slowing the user down

Coins jamming…

So, at present the user can just spam the coins button. And the coins jam up.

This isn't very realistic.

The Spawner should prevent the user from adding a new coin until the area for a coin is free.

First I notice that the coin prefab has had it's position moved for some reason, so resetting that to 0,0,0 helps a lot.

Now add that to the Spawn Location as a child, so it appears in the position that coins spawn from, in exactly the same position.

Next, from this coin, turn off the "Use Gravity" in the "Rigidbody", and turn on the "Is Trigger" in the "Mesh Collider".

We want to use the trigger functions to determine when something has started and finished touching the mesh and to work out when the areas is clear to spawn a new coin. Which is why I used a coin that will be in the same shape.

I've created a Component call "SpawnerBlockedDetector" …

public class SpawnerBlockedDetector : MonoBehaviour {

  public UnityEvent OnSpawnerBlocked = new UnityEvent();
  public UnityEvent OnSpawerClear = new UnityEvent();

  private void OnTriggerEnter(Collider other) {
     OnSpawnerBlocked.Invoke();
  }

  private void OnTriggerExit(Collider other) {
     OnSpawerClear.Invoke();
  }
}

It just passes on the OnTriggerEnter and OnTriggerExit events to a UnityEvent that can be bound in the IDE.

In the "spawner" object, in it's "SpanwerController" Component, I added a new "Spanwer Blocked" bool and altered the SpawnObject code to only allow objects to be spawned if it is set to false…

...
public bool spawnerBlocked = false;

// Use this for initialization
void Start () {
}

// Update is called once per frame
void Update () {

  if (Input.GetButtonDown("Fire1")) {
     SpawnObject();      
  }

}

void SpawnObject() {
  if (!spawnerBlocked) {
     var coin = Instantiate(ObjectToSpawn, transform);
     coin.transform.position = SpawnLocation.position;
     coin.transform.rotation = SpawnLocation.rotation;

     OnSpawnCoin.Invoke();
  }
}

public void SetSpawnerBlocked(bool value) {
  spawnerBlocked = value;
}
...

And in the IDE, in the 'coin', with the "SpawnerBlockedDetector" script, I get it to call this SetSpawnerBlocked with true or false values, depending on the situation…

Now… when you try and spam the 'fire' button it kinda mostly works. But to help it a little bit more, I also moved the Spawn Location 'Y' value to -0.2 to make sure the coins weren't catching and if there was any slight overlap, that they had a little wiggle room…

Also, finally, the coin, I disabled the "Mesh Renderer" so it's not visible, but is still firing the trigger….

Now even when trying your hardest, it doesn't let you go wild with the fire button… it can still jam, just not as easily…

GIT TAG 024_AddingSpamPrevention

Unity - A simple tutorial < Unity Tutorial 27 - More Refinements Unity Tutorial 29 - Some more changes >