Wednesday, 15 April 2020

Unity C# Creating dynamic lines using Line render

using System.Collections.Generic;
using UnityEngine;

//[RequireComponent(typeof(LineRenderer))]
public class LineRendererTest : MonoBehaviour
{
    List<Vector3> linePoints = new List<Vector3>();
    LineRenderer lineRenderer;
    public float startWidth = 1.0f;
    public float endWidth = 1.0f;
    public float threshold = 0.001f;
     public Camera thisCamera;
    int lineCount = 0;

    public GameObject linePrefab;
    public bool buttonPressed;
    public List<Vector3> mousePosArray;

    Vector3 lastPos = Vector3.one * float.MaxValue;


    void Awake()
    {
        thisCamera = Camera.main;
    }
    private void Start()
    {

    }
    void Update()
    {
       
        if (Input.GetMouseButton(0))
        {
            if(!buttonPressed)
            {
                linePoints.Clear();
                lineCount = 0;
                buttonPressed = true;
                CreateLine();
            }
        }
        if (Input.GetMouseButton(0))
        {
            UpdateLine();

        }
        if (Input.GetMouseButtonUp(0))
        {
         
            linePoints.Clear();
            lineCount = 0;
            buttonPressed = false;
        }
     
    }

    void CreateLine()
    {
       
        GameObject newLine = Instantiate(linePrefab, Input.mousePosition, Quaternion.identity);
        lineRenderer = newLine.GetComponent<LineRenderer>();

        Vector3 mousePos = Input.mousePosition;
        mousePos.z = thisCamera.nearClipPlane;
        Vector3 mouseWorld = thisCamera.ScreenToWorldPoint(mousePos);

        float dist = Vector3.Distance(lastPos, mouseWorld);
        if (dist <= threshold)
            return;

        lastPos = mouseWorld;
    }

    void UpdateLine()
    {
       
        Vector3 mousePos = Input.mousePosition;
        mousePos.z = thisCamera.nearClipPlane;
        Vector3 mouseWorld = thisCamera.ScreenToWorldPoint(mousePos);

        float dist = Vector3.Distance(lastPos, mouseWorld);
        if (dist <= threshold)
            return;

        lastPos = mouseWorld;
        if (linePoints == null)
            linePoints = new List<Vector3>();
        linePoints.Add(mouseWorld);

        lineRenderer.SetWidth(startWidth, endWidth);
        lineRenderer.SetVertexCount(linePoints.Count);

        for (int i = lineCount; i < linePoints.Count; i++)
        {
            lineRenderer.SetPosition(i, linePoints[i]);
        }
        lineCount++;
    }
}

Moving objects in Unity using C# code snippet

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

public class MoveObject : MonoBehaviour
{

    public float moveSpeed;

    // Use this for initialization
    void Start()
    {
        moveSpeed = 1f;
    }

    // Update is called once per frame
    void Update()
    {
        transform.Translate(moveSpeed * Input.GetAxis("Horizontal") * Time.deltaTime, 0f, moveSpeed * Input.GetAxis("Vertical") * Time.deltaTime);
    }
}

Accessing Camera feed in Unity using C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;

public class WebStream : MonoBehaviour
{
    public RawImage rawimage;
    WebCamTexture webCamTexture;

    public Text webCamDisplayText;

    void Start()
    {


        WebCamDevice[] cam_devices = WebCamTexture.devices;
        // for debugging purposes, prints available devices to the console
        for (int i = 0; i < cam_devices.Length; i++)
        {
            print("Webcam available: " + cam_devices[i].name);
        }
        GoWebCam01();
    }


    //CAMERA 01 SELECT
    public void GoWebCam01()
    {
        WebCamDevice[] cam_devices = WebCamTexture.devices;
        // for debugging purposes, prints available devices to the console
        for (int i = 0; i < cam_devices.Length; i++)
        {
            print("Webcam available: " + cam_devices[i].name);
        }

        webCamTexture = new WebCamTexture(cam_devices[0].name, 480, 640, 30);
        rawimage.texture = webCamTexture;
        if (webCamTexture != null)
        {
            webCamTexture.Play();
            Debug.Log("Web Cam Connected : " + webCamTexture.deviceName + "\n");
        }
        webCamDisplayText.text = "Camera Type: " + cam_devices[0].name.ToString();
    }
    //CAMERA 02 SELECT
    public void GoWebCam02()
    {
        WebCamDevice[] cam_devices = WebCamTexture.devices;
        // for debugging purposes, prints available devices to the console
        for (int i = 0; i < cam_devices.Length; i++)
        {
            print("Webcam available: " + cam_devices[i].name);
        }

        webCamTexture = new WebCamTexture(cam_devices[1].name, 480, 640, 30);
        rawimage.texture = webCamTexture;
        if (webCamTexture != null)
        {
            webCamTexture.Play();
            Debug.Log("Web Cam Connected : " + webCamTexture.deviceName + "\n");
        }
        webCamDisplayText.text = "Camera Type: " + cam_devices[1].name.ToString();
    }
}

Thursday, 14 November 2019

Unity C# Shooting a object along a trajectory

Create a new game object a sphere that will be the object that will be used for shooting, also create an empty game object and name it as a target. Copy the below script and attach it to a new empty game object and attach the sphere and target object in the inspector.


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

public class ShootingBall : MonoBehaviour
{
    public Transform myTarget;
    public GameObject snowballs;
    float shootAngle = 30;
    float angle;
    // Start is called before the first frame update
    public Vector3 BallisticVel(Transform target, float angle)
    {
        Vector3 dir = target.position - transform.position;
        float h = dir.y;  // get height difference
        dir.y = 0;  // retain only the horizontal direction
        float dist = dir.magnitude;  // get horizontal distance
        float a = angle * Mathf.Deg2Rad;  // convert angle to radians
        dir.y = dist * Mathf.Tan(a);  // set dir to the elevation angle
        dist += h / Mathf.Tan(a);  // correct for small height differences
                                   // calculate the velocity magnitude
        var vel = Mathf.Sqrt(dist * Physics.gravity.magnitude / Mathf.Sin(2 * a));
        return vel * dir.normalized;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown("b"))
        {  // press b to shoot
            GameObject ball = Instantiate(snowballs, transform.position, Quaternion.identity);
            ball.GetComponent<Rigidbody>().velocity = BallisticVel(myTarget, shootAngle);
            Destroy(ball, 10);
        }
    }
}

Wednesday, 5 June 2019

Learning's: Unity C# Parsing JSON data using SimpleJSON

Learning's: Unity C# Parsing JSON data using SimpleJSON: 1. Download the SimpleJSON .cs from this link and  https://github.com/Bunny83/SimpleJSON and create a folder called "plugin" un...

Unity C# Parsing JSON data using SimpleJSON


1. Download the SimpleJSON .cs from this link and https://github.com/Bunny83/SimpleJSON
and create a folder called "plugin" under unity project assets folder and place the SimpleJSON.cs script inside.

2. Create a new class called as SampleJSONParsing

3. Paste the below code on to the newly created class.

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


public class SampleJSONParsing :MonoBehaviour
{

    string encodedString = "{\"method\": \"retrieve_configuration\",\"params\": {\"configuration\" :\"109873839\"}}";

    void Start()
    {
        JSONNode jsonNode = SimpleJSON.JSON.Parse(encodedString);
        string action = jsonNode["params"][0].Value;
        Debug.Log(action);
    }


}

4. create a new scene attach the script to an empty game object and run the scene.

5. Similarly to parse your data pass it as a string.

Tuesday, 21 May 2019

Unity C# Sorting and Displaying Mesh Renderers in layers

1. Create a new C# script as "SetSortingLayer" and paste the below contents.
2. Attach the script to game objects with Mesh Renderers set the sorting layer. 0 being the lowest of the base layer and the top layer goes 0n increment



using UnityEngine;

 [ExecuteInEditMode]
 public class SetSortingLayer : MonoBehaviour {
     public Renderer MyRenderer;
     public string MySortingLayer;
     public int MySortingOrderInLayer;
   
     // Use this for initialization
     void Start () {
         if (MyRenderer == null) {
             MyRenderer = this.GetComponent<Renderer>();
         }
           

         SetLayer();
     }


     public void SetLayer() {
         if (MyRenderer == null) {
             MyRenderer = this.GetComponent<Renderer>();
         }
           
         MyRenderer.sortingLayerName = MySortingLayer;
         MyRenderer.sortingOrder = MySortingOrderInLayer;
       
         //Debug.Log(MyRenderer.sortingLayerName + " " + MyRenderer.sortingOrder);
     }
 
 }