logo

[N]oisyCrickets

Projects details

CLICK HERE TO RUN THOSE NOISY CRICKETS ON THE WEB – USE FIREFOX

Or download the PC Noisy Crickets App here – NoiseyCricket PC App

created at Mode Lab Experiments

A dynamic agent based pooling system operating under their own influences with an overarching perlin noise system. The app is fully functional as a PC build with a simplified web version. The agent in this case is a singe quad with a translucent “particle” like texture.

Behavioral Classes
Perlin MovementPerlin ControllerMap BehaviorSpawn BehaviorUpdate Value
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
//------------------------------------------------------------------------
//Perlin Noise Agents v1.0 - Perlin Noise Class
//--Class Controls the movements of the agents--Class lives in the SoloAgent Prefab which is used to instantiate--All behavioral changes must reference or update values from this class
//Mode Lab - Written by Luis Quinones
//------------------------------------------------------------------------
public class PerlinNoiseMovement : MonoBehaviour
{
    public float minSpeed = 0.1f;
    public float noiseScale = 75.0f;
    public float noiseStrength = 8.5f; 
    public bool proceed = true;
    private int offsetStep = 10000;
    public bool dimension;
    void Start(){

    }    
    void Update()
    {
        movement();
    }
    void movement()
    {
        if (proceed) {
            Transform currentPos = GetComponent<Transform>();
            if(dimension){ //2D NOISE
                float noiseVal = Mathf.PerlinNoise(currentPos.position.x / noiseScale, currentPos.position.z / noiseScale) * noiseStrength; //Get 2D Noise Value
                float angle = noiseVal;
                Vector3 newDirection = new Vector3(Mathf.Cos(angle), 0, Mathf.Sin(angle)); //Create Vector for new Direction
                Vector3 speed = new Vector3(Random.Range(-minSpeed, minSpeed), 0, Random.Range(-minSpeed, minSpeed)); //Vector for speed
                newDirection += speed;
                transform.Translate(newDirection); //Translate the position to the newPosition using the new vector

            }else if(dimension == false){ 

                float noiseVal = Mathf.PerlinNoise(currentPos.position.x / noiseScale, currentPos.position.z / noiseScale) * noiseStrength;
                float noiseValY = Mathf.PerlinNoise(currentPos.position.x / noiseScale + offsetStep, currentPos.position.y / noiseScale) * noiseStrength;
                
                float angle = noiseVal;
                float angleY = noiseValY;
                
                Vector3 newVec = new Vector3(0,0,0);
                
                newVec.x += Mathf.Cos (angleY) * Mathf.Cos (angle);
                newVec.y += Mathf.Cos (angleY) * Mathf.Sin (angle);
                newVec.z += Mathf.Sin (angleY);
                
                Vector3 newDirection = new Vector3(Mathf.Cos (angleY) * Mathf.Cos (angle), Mathf.Cos (angleY) * Mathf.Sin (angle), Mathf.Sin(angleY));
                Vector3 speed = new Vector3(Random.Range(-minSpeed, minSpeed), Random.Range(-minSpeed, minSpeed), Random.Range(-minSpeed, minSpeed));
                newDirection += speed;
            
                transform.Translate(newDirection);
            }
        }
    }    
}
Update
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
//------------------------------------------------------------------------
//Perlin Noise Agents v1.0 - Controller Class
//--Controller Class is the main controller and organizer of the data, most other classes will be accessed by the controller and vice versa
//Mode Lab - Written by Luis Quinones
//------------------------------------------------------------------------
public class Controller : MonoBehaviour {
    //Variables Assignment
    public GameObject mapGeo,spawnGeo,reboot,agentSet;
    public Vector3 spawnValues;
    public int AgentCount = 1000;
    public float lifetime = 5.0f;
    public float sWidth = 1.0f;
    public float eWidth = 0.1f;
    public float mP = 1.0f;
    public float dimensionBarValue,physicsBarValue,agentDisplay,agentDynamicSpawnState;
    public int sceneAgentCount,runTimesCheck;
    private float RSliderValue, GSliderValue, BSliderValue, spawnBarValue;
    //-----------------------------------------------------
    public Slider strengthSlider,scaleSlider,speedSlider,agentCountSlider,trailTimeSlider,trailStartWSlider,trailEndWSlider,multiplierSlider;
    //-----------------------------------------------------
    public Slider RSlider,GSlider,BSlider;
    //-----------------------------------------------------
    public Button resetButton, runImageButton, colorEnableButton, colorDisableButton, runSpawnImageButton;
    //-----------------------------------------------------
    public Canvas mainCanvas, visualCanvas, optCanvas;
    //-----------------------------------------------------
    public Scrollbar spawnScrollBar,dimensionScrollBar,physicsScrollBar,agentHeadBar,dynamicAgentSpawnScrollBar, gradientTextureScrollBar;
    //-----------------------------------------------------
    public Toggle strengthToggle, scaleToggle, speedToggle, trailSWToggle, trailEWToggle;
    //-----------------------------------------------------
    public Camera flatCamera,dimensionCamera;
    //-----------------------------------------------------
    public GameObject cube;
    //-----------------------------------------------------
    public Gradient newGradient;
    //-----------------------------------------------------
    private bool hideCanvas,showCanvas,hideVisualCanvas,showVisualCanvas,isOutside, runButtonOn, showOptCanvas, runSpawnButton, pause, pauseHold, reload;
    private bool testThis;
    public bool sTenaled { get; set; }
    public bool scTenaled { get; set; }
    public bool speedTenaled { get; set; }
    public bool trailSW { get; set; }
    public bool trailEW { get; set; }
    public bool colorEnable { get; set; }
    public bool colorDisable { get; set; }    
    //-----------------------------------------------------
    void Start()
    {
        flatCamera.enabled = true; //2d Camera
        dimensionCamera.enabled = false; //3d Camera
        cube.GetComponent<MeshRenderer>().enabled = false; //Physics Cube Renderer Disabled
        //-----------------------------------------------------
        //This is where we check for the Spawn Map Enable Button
        //if its pressed we kill the existing agents and call the SpawnMapAgents Funct.
        //-----------------------------------------------------
        runSpawnButton = false; 
        runSpawnImageButton.onClick.AddListener(delegate{
            runSpawnButton = true;
            if (!runSpawnButton) {
                SpawnAgents (); 
            } else if (runSpawnButton) {
                GameObject[] Instances = GameObject.FindGameObjectsWithTag("AGENTDUDE");
                foreach(GameObject t in Instances){
                    Destroy(t);
                }
                SpawnMapAgents();
            }
        });
        //-----------------------------------------------------
        if (!runSpawnButton) {
            SpawnAgents(); //if our SpawnButton Isnt enabled just run the regular spawn protocol
        }
        //-----------------------------------------------------
        mainCanvas.enabled = true;
        visualCanvas.enabled = true;
        isOutside = false;
        runButtonOn = false;    
        optCanvas.enabled = false;
        //-----------------------------------------------------
        agentCountSlider.onValueChanged.AddListener (delegate {
            AgentCount = Mathf.RoundToInt(agentCountSlider.value);
            if(Mathf.RoundToInt(agentDynamicSpawnState) == 1){
                if(sceneAgentCount < 1500){
                    SpawnAgents ();
                }else{
                    Debug.Log ("REACHED MAX AGENT COUNT, RESET SIM"); //Set Max Approx Agent Count
                }
            }
        });
        dynamicAgentSpawnScrollBar.onValueChanged.AddListener (delegate {
            agentDynamicSpawnState = dynamicAgentSpawnScrollBar.value; //Update the dAS Scrollbar value when its changed
        });
        trailTimeSlider.onValueChanged.AddListener (delegate {
            lifetime = trailTimeSlider.value; //Update the trail time scrollbar value when its changed
        });
        trailStartWSlider.onValueChanged.AddListener (delegate {
            sWidth = trailStartWSlider.value; //Update the trail start width value when its changed
        });
        trailEndWSlider.onValueChanged.AddListener (delegate {
            eWidth = trailEndWSlider.value; //Update the trail end width value when its changed
        });
        multiplierSlider.onValueChanged.AddListener (delegate {
            mP = multiplierSlider.value; //Update the mutiplier slider value when its changed
        });
        spawnScrollBar.onValueChanged.AddListener (delegate {
            spawnBarValue = spawnScrollBar.value; //Update the spawn value scrollbar when its changed
        });
        dimensionScrollBar.onValueChanged.AddListener (delegate {
            dimensionBarValue = dimensionScrollBar.value; //Update the 2d/3d scrollbar value when its changed
        });
        physicsScrollBar.onValueChanged.AddListener (delegate {
            physicsBarValue = physicsScrollBar.value; //Update the physics scrollbar value when its changed
        });
        agentHeadBar.onValueChanged.AddListener (delegate {
            agentDisplay = agentHeadBar.value; //Update the display agent head value when its changed
        });
        //-----------------------------------------------------
        RSlider.onValueChanged.AddListener (delegate {
            RSliderValue = RSlider.value; //Update the R color Slider value when its changed
        });
        GSlider.onValueChanged.AddListener (delegate {
            GSliderValue = GSlider.value; //Update the G color slider value when its changed
        });
        BSlider.onValueChanged.AddListener (delegate {
            BSliderValue = BSlider.value; //Update the B color slider value when its changed
        });
        //-----------------------------------------------------
        runImageButton.onClick.AddListener(delegate{
            runButtonOn = true; //Ensures the Behavior Map is activated when the Enable button is pressed
            optCanvas.enabled = true; //Turns on the components canvas for behavioral map
        });
    }
    void SpawnAgents()
    {
        for (int i = 0; i < AgentCount; i++)
        {
            Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, 161), 0, Random.Range(-spawnValues.z, spawnValues.z)); //Set random pos to spawn
            Quaternion spawnRotation = Quaternion.identity;
            Instantiate(agentSet, spawnPosition, spawnRotation); //create instance of the agent
        }
    }
    void SpawnMapAgents(){
        //Function to Spawn Agents when using the spawnMap
        for (int i = 0; i < AgentCount; i++)
        {
            Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, 161), 0, Random.Range(-spawnValues.z, spawnValues.z));
            Quaternion spawnRotation = Quaternion.identity;
            float lumCast = spawnCastHit(spawnPosition); //Call the castHit Function to retreive the pixel color value from the spawned pos
            if(lumCast < 0.5){
                i -=1 ;
            }else{
                Instantiate(agentSet, spawnPosition, spawnRotation); //Create instance only if the grayscale value is > than specified value above
            }
        }
    }
    public float behaviorCastHit(Vector3 pos){
        Color c;
        Vector3 currentpos = pos; //current passed position
        RaycastHit hit;
        var hitPoint = currentpos;
        Physics.Raycast (hitPoint,Vector3.down, out hit,Mathf.Infinity);
        Renderer rend = hit.transform.GetComponent<Renderer>(); //Retreive the rendered component from the hit object
        Texture2D test = mapGeo.GetComponent<MapBehavior> ().texture; //if we are using the behavior map retrieve the code component from the inherited geo then retreive texture
        c = test.GetPixelBilinear(hit.textureCoord2.x,hit.textureCoord2.y); //Get the color info at the hit coordinates
        float gScale = c.grayscale; //set grayscale
        return gScale;
    }
    public float spawnCastHit(Vector3 pos){
        Color c;
        Vector3 currentpos = pos; //current passed position
        RaycastHit hit;
        var hitPoint = currentpos;
        Physics.Raycast (hitPoint,Vector3.down, out hit,Mathf.Infinity);
        Renderer rend = hit.transform.GetComponent<Renderer>(); //Retreive the rendered component from the hit object
        Texture2D test = spawnGeo.GetComponent<SpawnBehavior>().text; //if we are using the behavior map retrieve the code component from the inherited geo then retreive texture
        c = test.GetPixelBilinear(hit.textureCoord2.x,hit.textureCoord2.y); //Get the color info at the hit coordinates
        float gScale = c.grayscale; //set grayscale
        return gScale;
    }
    void OnGUI(){
        //Behavior Canvas
        if (!hideCanvas) {
            mainCanvas.enabled = true;
        } else {
            mainCanvas.enabled = false;
        }
        //VisualCanvas Canvas
        if (!hideVisualCanvas) {
            visualCanvas.enabled = true;
        } else {
            visualCanvas.enabled = false;
        }
    }
    void Update(){
        //----------------------------------
        //Pause the Simulation using the P Key
        if(Input.GetKeyDown("p")){
            pause = !pause;
            if (pause){
                pauseHold = true;
            }else if(!pause){
                pauseHold = false;
            }
        }
        //R key will reload the application with the default values
        if (Input.GetKey ("r")) {
            reload = true;
        }
        if (reload) {
            reload = false;
            Application.LoadLevel (Application.loadedLevel);
        } 
        //----------------------------------
        //Toggles the Component Canvas by pressing space bar
        if(Input.GetKeyDown("space")){
            showOptCanvas = !showOptCanvas;
            if (showOptCanvas)
                optCanvas.enabled = true;
            else if(!showOptCanvas)
                optCanvas.enabled = false;
        }
        //----------------------------------
        //Behavior Canvas 
        if(Input.GetKeyDown("c")){
            hideCanvas = !hideCanvas;
            if (hideCanvas)
                showCanvas = true;
            else if(!hideCanvas)
                showCanvas = false;
        }
        if (Input.GetKeyDown ("w")) {
            mainCanvas.enabled = false;
            visualCanvas.enabled = false;
            optCanvas.enabled = false;
        }
        //----------------------------------
        //Visual Canvas
        if(Input.GetKeyDown("v")){
            hideVisualCanvas = !hideVisualCanvas;
            if (hideVisualCanvas)
                hideVisualCanvas = true;
            else if(!hideVisualCanvas)
                hideVisualCanvas = false;
        }
        //----------------------------------
        //Checks if we are resetting if not then proceed normally.
        if (reboot.GetComponent<DataPreserve>().fireUp == true ) { //Checks referenced class and components for trigger to reset
            Start ();
            reboot.GetComponent<DataPreserve>().restart = false; //restores that classes values for next run
            reboot.GetComponent<DataPreserve>().fireUp = false;
        }else {
            GameObject[] test = GameObject.FindGameObjectsWithTag ("AGENTDUDE"); //Get All objects with same tag
            sceneAgentCount = test.Length;
            foreach (GameObject t in test) { //Go Through each instance
                if (t == null) {
                    Debug.Log ("Cant Find Instance");
                } else {
                    if (Mathf.RoundToInt(agentDisplay) == 1) {
                        t.GetComponentInChildren<MeshRenderer>().enabled = false; //turns on or off agent head inherits value from scrollbar listener
                    } else if (Mathf.RoundToInt(agentDisplay) == 0) {
                        t.GetComponentInChildren<MeshRenderer>().enabled = true;
                    }
                    //----------------------------------
                    //Only if physics is enabled in the scrollbar
                    if(t.GetComponent<Rigidbody>()){
                        if(Mathf.RoundToInt(physicsBarValue) == 0){                    
                            t.GetComponent<Rigidbody>().mass = 0.01f;
                            t.GetComponent<BoxCollider>().enabled = false;                        
                        }else if(Mathf.RoundToInt(physicsBarValue) == 1){                        
                            cube.GetComponent<MeshRenderer>().enabled = true;
                            t.GetComponent<Rigidbody>().mass = 1f;
                            t.GetComponent<BoxCollider>().enabled = true;
                        }
                    }
                    if(Mathf.RoundToInt(dimensionBarValue) == 0){ //IF we set scrollbar to 3d we swap cameras and pass flag to the PerlinNoise Class
                        flatCamera.enabled = true;
                        dimensionCamera.enabled = false;
                        t.GetComponent<PerlinNoiseMovement>().dimension = true;
                    }else if(Mathf.RoundToInt(dimensionBarValue) == 1){
                        flatCamera.enabled = false;
                        dimensionCamera.enabled = true;
                        t.GetComponent<PerlinNoiseMovement>().dimension = false;
                    }
                    if (pauseHold) {
                        t.GetComponent<PerlinNoiseMovement>().proceed = false; //if key is pressed pass flag to perlin noise class to freeze agents.
                    }else if(!pauseHold){
                        t.GetComponent<PerlinNoiseMovement>().proceed = true; //if key is pressed pass flag to perlin noise class to freeze agents.
                    }
                    if(runButtonOn){ //if the Behavior Map Enable button is on
                        float lumValue = behaviorCastHit(t.transform.position); //call cast ray function to get color pixel value
                        if(sTenaled){ //if Strength Checkbox is enabled for map then use the grayscale value as multiplier to current settings for strength
                            t.GetComponent<PerlinNoiseMovement> ().noiseStrength = strengthSlider.value * mP * lumValue ; 
                        }else{
                            t.GetComponent<PerlinNoiseMovement> ().noiseStrength = strengthSlider.value * mP;
                        }
                        //---------------------------------------------------------------------------------------------
                        if(scTenaled){//if scale Checkbox is enabled for map then use the grayscale value as multiplier to current settings for scale
                            float lumAdjusted;
                            if(lumValue == 0.0f){
                                lumAdjusted = 0.1f;
                            }else{
                                lumAdjusted = lumValue;
                            }
                            t.GetComponent<PerlinNoiseMovement> ().noiseScale = scaleSlider.value * mP * lumAdjusted  ;
                        }else{
                            t.GetComponent<PerlinNoiseMovement> ().noiseScale = scaleSlider.value * mP   ;
                        }
                        //---------------------------------------------------------------------------------------------
                        if(speedTenaled){ //if speed Checkbox is enabled for map then use the grayscale value as multiplier to current settings for speed
                            t.GetComponent<PerlinNoiseMovement> ().minSpeed = speedSlider.value * lumValue;            
                        }else{
                            t.GetComponent<PerlinNoiseMovement> ().minSpeed = speedSlider.value;
                        }
                        //---------------------------------------------------------------------------------------------
                        if(trailSW){ //if trail Start Width Checkbox is enabled for map then use the grayscale value as multiplier to current settings             
                            t.GetComponent<TrailRenderer>().startWidth = sWidth * lumValue;
                        }else{
                            t.GetComponent<TrailRenderer>().startWidth = sWidth ;
                        }                
                        //---------------------------------------------------------------------------------------------
                        if(trailEW){ //if trail End Width Checkbox is enabled for map then use the grayscale value as multiplier to current settings     
                            t.GetComponent<TrailRenderer>().endWidth = eWidth * lumValue;
                        }else{
                            t.GetComponent<TrailRenderer>().endWidth = eWidth;
                        }
                        t.GetComponent<TrailRenderer>().time = lifetime; //for each instance grab the trail component and set the trail time to the current slider value
                        if(colorEnable && !colorDisable){ //If color enable button is pressed then adjust the tint of the trail
                            Color nColor = new Color(RSliderValue,GSliderValue,BSliderValue);
                            Material trail = t.GetComponent<TrailRenderer>().material;
                            trail.SetColor("_TintColor",nColor);
                        }    
                    }else if(!runButtonOn){ //If we are not using an image to drive values then run below
                    
                        t.GetComponent<PerlinNoiseMovement> ().noiseStrength = strengthSlider.value * mP;//For each instance we go into the Perlin Noise Class and set its variables to our slider values
                        t.GetComponent<PerlinNoiseMovement> ().noiseScale = scaleSlider.value * mP;//For each instance we go into the Perlin Noise Class and set its variables to our slider values
                        t.GetComponent<PerlinNoiseMovement> ().minSpeed = speedSlider.value;//For each instance we go into the Perlin Noise Class and set its variables to our slider values
                        
                        t.GetComponent<TrailRenderer>().startWidth = sWidth;//For each instance we go into the Perlin Noise Class and set its variables to our slider values
                        t.GetComponent<TrailRenderer>().endWidth = eWidth;//For each instance we go into the Perlin Noise Class and set its variables to our slider values
                        t.GetComponent<TrailRenderer>().time = lifetime;//For each instance we go into the Perlin Noise Class and set its variables to our slider values
                
                        if(colorEnable && !colorDisable){ //If color enable button is pressed then adjust the tint of the trail 
                            Color nColor = new Color(RSliderValue,GSliderValue,BSliderValue);
                            Material trail = t.GetComponent<TrailRenderer>().material;
                            trail.SetColor("_TintColor",nColor);
                        }
                    }
                    if(t.transform.position.x < -spawnValues.x || t.transform.position.x > 161 || t.transform.position.y < -spawnValues.y || t.transform.position.y > spawnValues.y || t.transform.position.z < -spawnValues.z || t.transform.position.z > spawnValues.z){
                        isOutside = true; //if agent position is outside the bounds we set the flag to pass along
                    }else{
                        isOutside = false;
                    }
                    if(isOutside){ //if its outside the bounds kill it and respawn a new one randomly inside the bounds
                        if(Mathf.RoundToInt(spawnBarValue) == 0){ //Value for constant spawn, here they will keep spawning as they go off frame
                            Destroy(t);
                            Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, 161), 0, Random.Range(-spawnValues.z, spawnValues.z));
                            Quaternion spawnRotation = Quaternion.identity;
                            Instantiate(agentSet, spawnPosition, spawnRotation);
                        }else if(Mathf.RoundToInt(spawnBarValue) == 1){ //value for die off, here they will stop moving once they are outside the bounds and will die once their trail time expires
                            t.GetComponent<PerlinNoiseMovement>().proceed = false;
                            Destroy(t,lifetime);
                        }
                    }                
                }
            }
        }
    }
}
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using System.IO;
//------------------------------------------------------------------------
//Perlin Noise Agents v1.0 - Map Behavior Class
//--Class Controls the enabling and disabling of the Behavioral Map Texture and display--Class is a component of the Map_Geometry Game Object which contains a single mesh quad
//Mode Lab - Written by Luis Quinones
//------------------------------------------------------------------------
public class MapBehavior : MonoBehaviour {
    public GameObject planeBehavior;
    private Renderer rend;
    public Texture2D texture;
    public Scrollbar toggleImage;
    private bool turnOn;
    private float toggleImageVal;
    public string updatePath;
    public bool runIt;

    void Start () {
        if (runIt) {
            runIt = false;
            turnOn = false;
            planeBehavior.GetComponent<MeshRenderer> ().enabled = false; //Turns off mesh rendered component to keep mesh hidden
            rend = GetComponent<Renderer> ();
            texture = new Texture2D (1024, 768); //Creates a new texture with the specified pixels        
            toggleImage.onValueChanged.AddListener (delegate {
                toggleImageVal = toggleImage.value; //Checks if we changed the scrollbar to display the mesh and texture
            });
            if(updatePath.Length != 0){    
                var bytes = File.ReadAllBytes(updatePath);
                texture.LoadImage(bytes); //Loads image
                rend.material.mainTexture = texture; //Assigns it to instance of material
                turnOn = true; //Turns on the mesh and texture            
            }else{
                return;
            }
        }
    }
    void Update () {
        if (runIt) {
            Start();
        }
        //turns on and off the mesh based on the display scrollbar value which has a listener attached to it in the start function
        if (Mathf.RoundToInt(toggleImageVal) == 1) {
            planeBehavior.GetComponent<MeshRenderer> ().enabled = true;
            //plane.GetComponent<MeshCollider> ().enabled = true;
        } else {
            planeBehavior.GetComponent<MeshRenderer> ().enabled = false;
            //plane.GetComponent<MeshCollider> ().enabled = false;
        }
    }
}
Update
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using System.IO;
//------------------------------------------------------------------------
//Perlin Noise Agents v1.0 - Spawn Behavior Class
//--Class Controls the enabling and disabling of the Spawn Map Texture and display--Class is a component of the Spawn_Geometry Game Object which contains a single mesh quad
//Mode Lab - Written by Luis Quinones
//------------------------------------------------------------------------
public class SpawnBehavior : MonoBehaviour {
    public GameObject plane;
    private Renderer rend;
    public Texture2D text;
    public Scrollbar toggleImage;
    private bool turnOn;
    private float toggleImageVal;
    public string newPath;
    public bool runIt;
    void Start () {
        if (runIt) {    
            runIt = false;
            turnOn = false;
            plane.GetComponent<MeshRenderer> ().enabled = false; //Turns off mesh rendered component to keep mesh hidden
            rend = GetComponent<Renderer> ();
            text = new Texture2D (1024, 768); //Creates a new texture with the specified pixels
            toggleImage.onValueChanged.AddListener (delegate {
                toggleImageVal = toggleImage.value; //Checks if we changed the scrollbar to display the mesh and texture
            });    
            if (newPath.Length != 0) {        
                var bytes = File.ReadAllBytes (newPath);
                text.LoadImage (bytes);//Loads image                
                rend.material.mainTexture = text;//Assigns it to instance of material
                turnOn = true; //Turns on the mesh and texture            
            } else {    
                return;
            }
        }
    }
    void Update () {
        if (runIt) {
            Start();
        }
        //turns on and off the mesh based on the display scrollbar value which has a listener attached to it in the start function
        if (Mathf.RoundToInt(toggleImageVal) == 1) {
            plane.GetComponent<MeshRenderer> ().enabled = true;
            //plane.GetComponent<MeshCollider> ().enabled = true;
        } else {
            plane.GetComponent<MeshRenderer> ().enabled = false;
            //plane.GetComponent<MeshCollider> ().enabled = false;
        }
    }
}
Update
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
//------------------------------------------------------------------------
//Perlin Noise Agents v1.0 - Update Values Class
//--Class controls the updates to the text box when used with the agent count slider
//Mode Lab - Written by Luis Quinones
//------------------------------------------------------------------------
public class UpdateValue : MonoBehaviour {
    public Text text;
    public Slider AgentCountSlider;
    public Controller control;
    void Update(){
        text.text = control.sceneAgentCount.ToString();
    }
}
Write|Read|Data Classes
Data PreserveFile BrowserSettings ExportSettings ImportScreen GrabWrite FileWrite Settings
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
//------------------------------------------------------------------------
//Perlin Noise Agents v1.0 - Data Preserve Class
//--Class controls the resetting process, flags and triggers are passed to the Controller once resetting is verified--Class is a component of the Data Preserve Empty Game Object--
//--Previous User Values are kept in the resetting process, we use the flag to recall spawn functions once we have killed off the agents
//Mode Lab - Written by Luis Quinones
//------------------------------------------------------------------------
public class DataPreserve : MonoBehaviour {
    public Controller control;
    public Button resetButton;
    public bool restart { get; set; }
    public bool fireUp;
    void Start(){
        resetButton.onClick.AddListener (delegate { //checks for the click on the reset button
            restart = true;
            if (restart) {            
                GameObject[] test = GameObject.FindGameObjectsWithTag ("AGENTDUDE");
                foreach (GameObject t in test) {                
                    Destroy(t); //Kill all agents                
                }
                fireUp = true; //Set flags to be retreived by the controller 
                restart = false; //Set flags to be retreived by the controller 
            }
        });
    }
}
Update
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class FileBrowser : MonoBehaviour {
    string message = "";
    float alpha = 1.0f;
    char pathChar = '/';
    public float posY = 560;
    public float posX = 560;
    public float posY2 = 739;
    public float posX2 = 18;
    public float xSize = 159;
    public float ySize = 20;
    public Button check;
    private bool importCheck, importCheckPass, spawnCheckPass ;
    private bool importSettingCheck, importSettingCheckPass, exportSettingCheckPass;
    public GameObject mapBehaviorObj;
    public GameObject spawnBehaviorObj;
    public Controller control;
    
    void Start () {
        if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer) {
            pathChar = '\\';
        }
        importCheck = false;
        importSettingCheck = false;
    }
    void Update(){
        if (Input.GetKeyDown ("v") || Input.GetKeyDown("w")) {
            importCheck = !importCheck;
            if (importCheck){
                importCheckPass = true;
                spawnCheckPass = true;
            }else if (!importCheck){
                importCheckPass = false;
                spawnCheckPass = false;
            }
        }
        if (Input.GetKeyDown ("c") || Input.GetKeyDown("w")) {
            importSettingCheck = !importSettingCheck;
            if (importSettingCheck){
                importSettingCheckPass = true;
                exportSettingCheckPass = true;
            }else if (!importSettingCheck){
                importSettingCheckPass = false;
                exportSettingCheckPass = false;
            }
        }
    }
    void OnGUI () {
        if (!importCheckPass) {
            if (GUI.Button (new Rect(850, 562, 90, 30), "Import Map")) {
                if (UniFileBrowser.use.allowMultiSelect) {
                    UniFileBrowser.use.OpenFileWindow (OpenFiles);
                }
                else {
                    UniFileBrowser.use.OpenFileWindow (OpenFile);
                }
            }
        }
        if (!spawnCheckPass) {
            if (GUI.Button (new Rect(850, 662, 90, 31), "Spawn Map")) {
                if (UniFileBrowser.use.allowMultiSelect) {
                    UniFileBrowser.use.OpenFileWindow (OpenSpawnFiles);
                }
                else {
                    UniFileBrowser.use.OpenFileWindow (OpenSpawnFile);
                }
            }
        }
        if (!importSettingCheckPass) {
            if (GUI.Button (new Rect(posX2, posY2, xSize, ySize), "Import Settings")) {
                if (UniFileBrowser.use.allowMultiSelect) {
                    UniFileBrowser.use.OpenFileWindow (OpenFiles);
                }
                else {
                    UniFileBrowser.use.OpenFileWindow (OpenSettingFile);
                }
            }
        }
        if (!exportSettingCheckPass) {
            if (GUI.Button (new Rect(posX, posY, xSize, ySize), "Export Settings")) {
                UniFileBrowser.use.SaveFileWindow (SaveFile);
            }
        }
        var col = GUI.color;
        col.a = alpha;
        GUI.color = col;
        GUI.Label (new Rect(100, 275, 500, 1000), message);
        col.a = 1.0f;
        GUI.color = col;
    }
    void OpenFile (string behaviorpathToFile) {
        var behaviorfileIndex = behaviorpathToFile;
        //message = "You selected file: " + pathToFile.Substring (fileIndex+1, pathToFile.Length-fileIndex-1);
        mapBehaviorObj.GetComponent<MapBehavior> ().updatePath = behaviorfileIndex;
        mapBehaviorObj.GetComponent<MapBehavior> ().runIt = true;
        Fade();
    }
    void OpenSpawnFile (string spawnpathToFile) {
        var spawnfileIndex = spawnpathToFile;
        //message = "You selected file: " + pathToFile.Substring (fileIndex+1, pathToFile.Length-fileIndex-1);
        spawnBehaviorObj.GetComponent<SpawnBehavior> ().newPath = spawnfileIndex;
        spawnBehaviorObj.GetComponent<SpawnBehavior> ().runIt = true;
        Fade();
    }
    void OpenSettingFile (string pathToFile) {
        var fileIndex = pathToFile;
        //message = "You selected file: " + pathToFile.Substring (fileIndex+1, pathToFile.Length-fileIndex-1);
        control.GetComponent<SettingsImport> ().path = fileIndex;
        control.GetComponent<SettingsImport> ().runIt = true;
        Fade();
    }
    void OpenSpawnFiles (string[] pathsToFiles) {
        message = "You selected these files:\n";
        for (var i = 0; i < pathsToFiles.Length; i++) {
            var fileIndex = pathsToFiles[i].LastIndexOf (pathChar);
            message += pathsToFiles[i].Substring (fileIndex+1, pathsToFiles[i].Length-fileIndex-1) + "\n";
        }
        Fade();
    }
    void OpenFiles (string[] pathsToFiles) {
        message = "You selected these files:\n";
        for (var i = 0; i < pathsToFiles.Length; i++) {
            var fileIndex = pathsToFiles[i].LastIndexOf (pathChar);
            message += pathsToFiles[i].Substring (fileIndex+1, pathsToFiles[i].Length-fileIndex-1) + "\n";
        }
        Fade();
    }
    void SaveFile (string pathToFile) {
        var fileIndex = pathToFile;
        //message = "You're saving file: " + pathToFile.Substring (fileIndex+1, pathToFile.Length-fileIndex-1);
        control.GetComponent<SettingsExport> ().pathSpecified = fileIndex;
        control.GetComponent<SettingsExport> ().runIt = true;
        Fade();
    }
    void OpenFolder (string pathToFolder) {
        message = "You selected folder: " + pathToFolder;
        Fade();
    }
    void Fade () {
        StopCoroutine ("FadeAlpha");    // Interrupt FadeAlpha if it's already running, so only one instance at a time can run
        StartCoroutine ("FadeAlpha");
    }
    IEnumerator FadeAlpha () {
        alpha = 1.0f;
        yield return new WaitForSeconds (5.0f);
        for (alpha = 1.0f; alpha > 0.0f; alpha -= Time.deltaTime/4) {
             yield return null;
        }
        message = "";
    }
}
Update
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using System.IO;
//------------------------------------------------------------------------
//Perlin Noise Agents v1.0 - Settings Export Class
//--Class Controls the exporting of settings to a text file--Class lives inside the GameController Game Object--The Export Settings button lives in this class
//Mode Lab - Written by Luis Quinones
//------------------------------------------------------------------------
public class SettingsExport : MonoBehaviour {
    public Button ExportSettingsButton;
    public Controller control; //Reference the contoller
    StreamWriter sw; //Implements a textwriter for writing characters to a stream in a particular encoding
    private string newfilename;
    private bool writeFile;
    public string pathSpecified;
    public bool runIt;
    void Start(){
        if (runIt) {
            runIt = false;
            if (pathSpecified.Length != 0) {
                print ("Exported Settings");
                writeFile = true;
            } else {
                return; //Exit if the user hits cancel or does not specify a name for the file
            }
        }
    }
    void Update(){
        if (runIt) {
            Start();
        }
        if (writeFile) {
            WriteToFile(pathSpecified); //Call the write to file function and pass the path
            writeFile = false; //Set the flag to false after we do it once since its in the update function
        }
    }
    public void WriteToFile(string file)
    {
        sw = new StreamWriter(file);
        //Write all the values, use the sw.WriteLine to begin a new line after the value is written
        sw.Write (control.strengthSlider.value.ToString ()); 
        sw.WriteLine();
        sw.Write (control.scaleSlider.value.ToString ());
        sw.WriteLine();
        sw.Write (control.speedSlider.value.ToString ());
        sw.WriteLine();
        sw.Write (control.multiplierSlider.value.ToString ());
        sw.WriteLine();
        sw.Write (control.agentCountSlider.value.ToString ());
        sw.WriteLine();
        sw.Write (control.dynamicAgentSpawnScrollBar.value.ToString ());
        sw.WriteLine ();
        sw.Write (control.spawnScrollBar.value.ToString ());
        sw.WriteLine ();
        sw.Write (control.dimensionScrollBar.value.ToString ());
        sw.WriteLine ();
        sw.Write (control.physicsScrollBar.value.ToString ());
        sw.WriteLine ();
        sw.Write (control.trailTimeSlider.value.ToString ());
        sw.WriteLine();
        sw.Write (control.trailStartWSlider.value.ToString ());
        sw.WriteLine();
        sw.Write (control.trailEndWSlider.value.ToString ());
        
        sw.Close ();
    }
}
Update
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using System;
using System.IO;
//------------------------------------------------------------------------
//Perlin Noise Agents v1.0 - Settings Import Class
//--Class Controls the importing of settings from a text file--Class lives inside the GameController Game Object--The Import Settings button lives in this class
//Mode Lab - Written by Luis Quinones
//------------------------------------------------------------------------
public class SettingsImport : MonoBehaviour {
    public Button ImportSettingsButton;
    public Controller control;
    public DataPreserve dp;
    public string path;
    public bool runIt;
    //ORDER OF TEXT DATA
    //strengthSlider | scaleSlider | speedSlider | multiplierslider | agentcountslider | dynamicagentspawnscrollbar | spawnscrollbar | dimensionscrollbar | physicsscrollbar | trailtimeslider | trailstartwidth | trailendwidth
    void Start(){
        if (runIt) {
            runIt = false;
            List<dynamic> valueList = new List<dynamic> ();
            valueList.Add (control.strengthSlider);
            valueList.Add (control.scaleSlider);
            valueList.Add (control.speedSlider);
            valueList.Add (control.multiplierSlider);
            valueList.Add (control.agentCountSlider);
            valueList.Add (control.dynamicAgentSpawnScrollBar);
            valueList.Add (control.spawnScrollBar);
            valueList.Add (control.dimensionScrollBar);
            valueList.Add (control.physicsScrollBar);
            valueList.Add (control.trailTimeSlider);
            valueList.Add (control.trailStartWSlider);
            valueList.Add (control.trailEndWSlider);
            if (path.Length != 0) {
                StreamReader sr = new StreamReader (path); //Set a new path to the streamreader
                var fileContents = sr.ReadToEnd (); //Read the file
                sr.Close ();        
                var lines = fileContents.Split ("\n" [0]); //Split the lines we are using a workaround in Unity Script because unity doesnt have character literals. we are using a string
                //and taking the first character [0] as the splitting delimiter.
                int count = 0;
                foreach (var line in lines) {    //For each line that is read we are assigning the line value which is converted to a float to the corresponding values in the Controller Class
                    print("LINE = " + line);
                    if (count == 0) {
                        control.strengthSlider.value = float.Parse (line);
                    }
                    if (count == 1) {            
                        control.scaleSlider.value = float.Parse (line);
                    }
                    if (count == 2) {                
                        control.speedSlider.value = float.Parse (line);
                    }
                    if (count == 3) {                    
                        control.multiplierSlider.value = float.Parse (line);
                    }
                    if (count == 4) {                
                        control.agentCountSlider.value = float.Parse (line);
                    }
                    if (count == 5) {                
                        control.dynamicAgentSpawnScrollBar.value = float.Parse (line);
                    }
                    if (count == 6) {                    
                        control.spawnScrollBar.value = float.Parse (line);
                    }
                    if (count == 7) {                
                        control.dimensionScrollBar.value = float.Parse (line);
                    }
                    if (count == 8) {                    
                        control.physicsScrollBar.value = float.Parse (line);
                    }
                    if (count == 9) {                    
                        control.trailTimeSlider.value = float.Parse (line);
                    }
                    if (count == 10) {                
                        control.trailStartWSlider.value = float.Parse (line);
                    }
                    if (count == 11) {                
                        control.trailEndWSlider.value = float.Parse (line);
                    }
                    count ++;
                }
                GameObject[] test = GameObject.FindGameObjectsWithTag ("AGENTDUDE");
                foreach (GameObject t in test) {        
                    Destroy (t); //Kill all agents                
                }
                control.reboot.GetComponent<DataPreserve> ().fireUp = true; //Pass the reset flag to the Controller
            } else {            
                return;
            }
        }
    }
    void Update(){
        if (runIt) {
            Start();
        }    
    }
}
Update
using UnityEngine;
using System.Collections;
//------------------------------------------------------------------------
//Perlin Noise Agents v1.0 - ScreenGrab Class
//--Class Controls the ScreenCapture process--Class lives as a component in the main Camera
//Mode Lab - Written by Luis Quinones
//------------------------------------------------------------------------
public class QuickScreenGrab : MonoBehaviour {
    void Update(){
        if (Input.GetKey ("q")) { 
            Application.CaptureScreenshot ("ScreenShot.png",4);
            Debug.Log("Took ScreenShot with UI");
        }
        if (Input.GetKey ("w")) {
            Application.CaptureScreenshot ("ScreenShot.png",4);
            Debug.Log("Took ScreenShot without UI");    
        }
    }
}
using UnityEngine;
using System.Collections;
using System.IO;
//------------------------------------------------------------------------
//Perlin Noise Agents v1.0 - Write File Class
//--Class controls the writing of agent Positions to a text file--Class lives inside the GameController Game Object--
//Mode Lab - Written by Luis Quinones
//------------------------------------------------------------------------
public class WriteFile : MonoBehaviour 
{
    StreamWriter sw;
    string path = "Assets/Files/";
    string filename = "AgentPositions.txt";
    private string newfilename;
    void Start()
    {
        if(!Directory.Exists(path))
            Directory.CreateDirectory(path);
        else
        {
            if(!File.Exists(filename))
                File.Create(path+filename);
        }
    }
    void Update(){
        if (Input.GetKey ("f6")) {
            string theTime = System.DateTime.Now.ToString("hh.mm.ss"); 
            string theDate = System.DateTime.Now.ToString("MM-dd-yyyy"); 
            Application.CaptureScreenshot("Screenshot_" + theTime.ToString() + "_" + theDate.ToString() + ".png",4);
            Debug.Log ("Took ScreenShot with UI and Exported Text File with Positions");    
            newfilename = "AgentPositions_" + theTime.ToString() + "_" + theDate.ToString() + ".txt";    
            WriteToFile(path+newfilename);    
        }
    }
    public void WriteToFile(string file)
    {
        sw = new StreamWriter(file);
        GameObject[] test = GameObject.FindGameObjectsWithTag ("AGENTDUDE");
        int count = 0;
        foreach (GameObject t in test) {
            if (t == null) {
                Debug.Log ("Cant Find Instance");
            } else {
                sw.WriteLine (t.transform.position.ToString ());
                count ++;
            }
        }
        sw.Close ();
    }
}
Update
using UnityEngine;
using System.Collections;
using System.IO;
//------------------------------------------------------------------------
//Perlin Noise Agents v1.0 - Write Settings Class
//--Class controls the writing of settings to a text file, different than export, here we are listing the variable names and values--Class lives in the Game Controller Game Object--
//Mode Lab - Written by Luis Quinones
//------------------------------------------------------------------------
public class WriteSettings : MonoBehaviour 
{
    public Controller control;
    StreamWriter sw;
    string pathSetting = "Assets/Files/";
    string settingfilename = "AgentSettings.txt";
    string longPath = "Assets/Files/AgentSettings.txt";
    private string newfilename;
    void Start()
    {
        //Check to see if directory and files exist
        if(!Directory.Exists(pathSetting))
            Directory.CreateDirectory(pathSetting);
        else
        {
            if(!File.Exists(settingfilename))
                File.Create(pathSetting+settingfilename);
        }
    }
    void Update(){
        if (Input.GetKey ("f7")) { //Use the f7 key to capture screenshot with UI and export the text file with settings
            string theTime = System.DateTime.Now.ToString("hh.mm.ss"); 
            string theDate = System.DateTime.Now.ToString("MM-dd-yyyy"); 
            Application.CaptureScreenshot("ScreenshotSettings_" + theTime.ToString() + "_" + theDate.ToString() + ".png",4);
            Debug.Log ("Took ScreenShot with UI and Exported Agent Settings");    
            newfilename = "AgentSettings_" + theTime.ToString() + "_" + theDate.ToString() + ".txt";
            WriteToFile(pathSetting+newfilename);
        }
        if (Input.GetKey ("f10")) {         
            if(Directory.Exists(pathSetting)){
                print ("Directory Exists");
                if(File.Exists(longPath)){
                    print ("file exists");
                }
            }
        }
    }
    public void WriteToFile(string file)
    {
        sw = new StreamWriter(file);
        sw.Write ("Strength Slider Value = " + control.strengthSlider.value.ToString ());
        sw.WriteLine();
        sw.Write ("Scale Slider Value = " + control.scaleSlider.value.ToString ());
        sw.WriteLine();
        sw.Write ("Speed Slider Value = " + control.speedSlider.value.ToString ());
        sw.WriteLine();
        sw.Write ("Multiplier Slider Value = " + control.multiplierSlider.value.ToString ());
        sw.WriteLine();
        sw.Write ("Agent Count Slider Value = " + control.agentCountSlider.value.ToString ());
        sw.WriteLine();
        if (control.dynamicAgentSpawnScrollBar.value == 0) {
            sw.Write ("Dynamic Spawn Scroll Bar Value Value = Static");
            sw.WriteLine();
        } else {
            sw.Write ("Dynamic Spawn Scroll Bar Value Value = Dynamic");
            sw.WriteLine();
        }
        if (control.spawnScrollBar.value == 0) {
            sw.Write ("Spawn Scroll Bar Value Value = Constant");
            sw.WriteLine();
        } else {
            sw.Write ("Spawn Scroll Bar Value Value = DieOff");
            sw.WriteLine();
        }
        if (control.dimensionScrollBar.value == 0) {
            sw.Write ("Dimension = 2D");
            sw.WriteLine();
        } else {
            sw.Write ("Dimension = 3D");
            sw.WriteLine();
        }
        if (control.physicsScrollBar.value == 0) {
            sw.Write ("Environment = Behavior");
            sw.WriteLine();
        } else {
            sw.Write ("Environment = Physics");
            sw.WriteLine();
        }
        sw.Write ("Trail Time Value = " + control.trailTimeSlider.value.ToString ());
        sw.WriteLine();
        sw.Write ("Trail StartWidth Value = " + control.trailStartWSlider.value.ToString ());
        sw.WriteLine();
        sw.Write ("Trail EndWidth Value = " + control.trailEndWSlider.value.ToString ());
        sw.WriteLine();
        sw.Close ();
    }
}
Update

 

  • Share

Leave a reply

Your email address will not be published. Required fields are marked *