пятница, 30 мая 2014 г.

Simple one way platform Unity3D 2D

Here is a simple script for OWP. To use it you must define layer for player and two layers for platform object, one of them is just layer for active platform and other for inactive with disabled collision with player layer.



Then you need to select disabled platform layer fo platform. After that attach OWP script and specify layer names in inspector.



Here is a script:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[RequireComponent(typeof(Collider2D))]
public class OneWayPlatform : MonoBehaviour {
public string PlayerLayerName = string.Empty;
public string EnabledPlatformLayer = string.Empty;
public string DisabledPlatformLayer = string.Empty;
private GameObject ParentGO;
private int playerLayer = -1;
private int enabledPlatform = -1;
private int disabledPlatform = -1;

private GameObject player = null;
// Use this for initialization
void Start () {
if(PlayerLayerName == string.Empty) Debug.LogError("PLAYER LAYER UNDEFINED");
ParentGO = gameObject.transform.parent.gameObject;
playerLayer = LayerMask.NameToLayer(PlayerLayerName);
enabledPlatform = LayerMask.NameToLayer(EnabledPlatformLayer);
disabledPlatform = LayerMask.NameToLayer(DisabledPlatformLayer);

try{
player = FindGameObjectsWithLayer(playerLayer)[0];
} catch {
Debug.LogError("NO PLAYER FOUND");
}
}


GameObject[] FindGameObjectsWithLayer (int layer) {
GameObject[] goArray = FindObjectsOfType(typeof(GameObject)) as GameObject[];
List goList = new List();
for (int i = 0; i < goArray.Length; i++) {
if (goArray[i].layer == layer) {
goList.Add(goArray[i]);
}
}
if (goList.Count == 0) {
return null;
}
return goList.ToArray();
}
void Update(){
if(player.transform.position.y > transform.position.y){
if(gameObject.layer != enabledPlatform){
gameObject.layer = enabledPlatform;
}
} else {
if(gameObject.layer != disabledPlatform){
gameObject.layer = disabledPlatform;
}
}
}
}