Random Code: Bottomless Pits

Feeling random today, so I’m starting a new series of posts where I give examples of the code I have used in my games, written in Javascript, and for use with Unity. Today I will post some code that will run when the player falls off a level. First you need a collider of some kind placed below the level; make it wide enough so that your player always lands on it when they fall of the level, and as far down as you want (but not so far it will take ages to fall to it). Make sure the collider is a trigger, then attach to it a script containing this code:

function OnTriggerEnter(other: Collider)
{
    if(other.tag == "Player")
    {
        other.SendMessage("Die", SendMessageOptions.DontRequireReceiver);
    }
    else
    {
        Destroy(other.gameObject);
    }
}

This code basically checks if the collider falling into the trigger is tagged “Player”, and if so, it will send the message “Die” to the object, which will call the Die() function in any scripts attached to the player; this is useful for putting some respawn code in the Die() function, so the player gets respawned whenever they fall off the level. If the object isn’t tagged “Player”, then it simply gets destroyed, so enemies and scenery will just disappear rather than fall indefinitely. Just remember to tag your player as “Player”, and then you’re good to go! Also, it would help if someone could tell me why WordPress is colossally bad at letting me indent text, it was a pain to type this post, but I hope it helps anyway.

—————————————————

I’m also making progress with Project Spikes, and another update will come around pretty soon. For now, a teaser image!

spikes-11Yeah, grayscale images ftw! Anyway, happy coding peoples!

 

 

Advertisements