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);
     }
 
 }

Monday, 20 May 2019

Unity C# - Hololens Creating an intractable model on Run time

To attach a script to a game object as component during run time, create a new C# script  and paste the below contents.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using HoloToolkit.Unity.InputModule.Utilities.Interactions;

public class AttachScript : MonoBehaviour
{
    public GameObject  DmuModel;

    void Start()
    {
         Transform[] allchild = DmuModel.GetComponentsInChildren<Transform>();
           foreach (Transform child in allchild)
             {

              child.gameObject.AddComponent<MeshCollider>();
               child.gameObject.AddComponent<TwoHandManipulatable>();
           }

    }

}

Monday, 13 May 2019

3D Text Mesh Wrapping in Unity using C#

To use the text mesh wrapper snippet create a new 3D Text component in unity and then create a new C# script and name it as "WrapText" and replace the content with the below code snippet.

Then attach the code to the 3D text mesh  and under the 'Text Mesh" field in Wrap text component drag the same 3D text mesh.

Under the Max Line Chars field you can set the length of a particular sentence.

That's  it.

-------CODE SNIPPET-------------------COPY THE BELOW CONTENT-------------------------

using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class WrapText : MonoBehaviour
{
    public TextMesh textMesh;

    public int maxLineChars = 35;
    private int lastMaxLineChars = 35;

    string wrappedText = "";
    public bool disableWhilePlaying = true;

    void Awake()
    {
       // bool shouldDisable = disableWhilePlaying  !(Application.isEditor  !Application.isPlaying);
       // this.enabled = !shouldDisable;
    }

    void Update()
    {
        if (textMesh.text != wrappedText || maxLineChars != lastMaxLineChars)
        {
            int charCount = 0;
            wrappedText = "";
            string line = "";

            char[] separators = new char[] { ' ', '\n', '\t' };
            string[] words = textMesh.text.Split(separators);

            for (int i = 0; i < words.Length; i++)
            {
                string word = words[i].Trim();

                if (i == 0)
                {
                    line = word;
                    charCount = word.Length;
                }
                else
                {
                    if ((charCount + (charCount > 0 ? 1 : 0) + word.Length) <= maxLineChars)
                    {
                        if (charCount > 0)
                        {
                            line += ' ';
                            charCount += 1;
                        }

                        line += word;
                        charCount += word.Length;
                    }
                    else
                    {
                        if (wrappedText.Length > 0)
                            wrappedText += '\n';

                        wrappedText += line;

                        line = word;
                        charCount = word.Length;
                    }
                }
            }

            if (charCount > 0)
            {
                if (wrappedText.Length > 0)
                    wrappedText += '\n';

                wrappedText += line;
            }

            textMesh.text = wrappedText;
            lastMaxLineChars = maxLineChars;
        }
    }
}

Friday, 15 February 2019

Creating Transparent text effect in Photoshop

At the end of this post we will be able to create a transparent text effect as shown below.


Getting started
1. Download an image which we will be using as BG.
2. Draw a new rectangle shape with white fill and reduce its opacity to 40%.
3. Create a sample text and position it above the white strip on the layers

4. Double click on the text layer to open up the Layers Style and apply stroke, increase the size to 250, position to Inside, Blend Mode to Overlay and opacity to 30.
5. Now add one more stroke and set its size to 2 position outside and opacity to 16.

That's it.

Monday, 14 January 2019

Unity C# 3D Progress bar - Creating a Progress bar which scales over time

1. Create a progress bar with outer frame(fixed) and a inner slider (scales over time) something as shown in the below pic.
2. Attach the below script to an empty game object and drag the slider game object on to the progress slider



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

public class ProgressBar : MonoBehaviour
{
    public GameObject progressSlider;
    float totalWidth;
    float totalDuration = 100.0f;
    float currentTime;
    float currentWidth;


// Use this for initialization
void Start ()
    {
        totalWidth = progressSlider.transform.localScale.x;
        currentWidth = totalWidth / 100;
        progressSlider.transform.localScale = new Vector3(currentWidth, progressSlider.transform.localScale.y, progressSlider.transform.localScale.z);


    }

// Update is called once per frame
void Update ()
    {
        currentTime += Time.deltaTime;
        if(currentTime<totalDuration )
        {
            if(currentWidth <= totalWidth)
            {
                currentWidth += 0.01f;
                progressSlider.transform.localScale = new Vector3(currentWidth, progressSlider.transform.localScale.y, progressSlider.transform.localScale.z);
            }
           
        }


    }
}


That's it run the scene.

Creating a Dictation Recognizer in Unity C# - Hololens

1.Create a new scene and apply the mixed reality scene settings.
2. Create a UI text component and drag on to the inputtext field on the next step after attaching the code.
2. Create a new button and attach the below script and trigger the InitateRecording function on click event


using UnityEditor;

using UnityEngine.UI;
using UnityEngine;
using HoloToolkit.Unity.InputModule;
using UnityEngine.Windows.Speech;

public class DictationHandler : MonoBehaviour {

   
    public GameObject inputtext = null, icon = null;
    public Material recording = null, stopped = null;
 
         [SerializeField]
    private Text m_Hypotheses;

    [SerializeField]
    private Text m_Recognitions;

    private DictationRecognizer m_DictationRecognizer;

    bool isRecording;

    public void InitateRecording()
    {
        if(!isRecording)
        {
            isRecording = true;
            StartRecording();
        }
        else
        {
            isRecording = false;
            StopRecording();
        }
    }

     void StartRecording()
    {
        icon.GetComponent<MeshRenderer>().material = recording;
        m_DictationRecognizer = new DictationRecognizer();

        m_DictationRecognizer.DictationResult += (text, confidence) =>
        {
            Debug.LogFormat("Dictation result: {0}", text);
            inputtext.GetComponent<UnityEngine.UI.Text>().text += text ;
        };

        m_DictationRecognizer.DictationHypothesis += (text) =>
        {
            Debug.LogFormat("Dictation hypothesis: {0}", text);
            m_Hypotheses.text += text;
        };

        m_DictationRecognizer.DictationComplete += (completionCause) =>
        {
            if (completionCause != DictationCompletionCause.Complete)
                Debug.LogErrorFormat("Dictation completed unsuccessfully: {0}.", completionCause);
        };

        m_DictationRecognizer.DictationError += (error, hresult) =>
        {
            Debug.LogErrorFormat("Dictation error: {0}; HResult = {1}.", error, hresult);
        };

        m_DictationRecognizer.Start();
    }
     void StopRecording()
    {
        m_DictationRecognizer.Stop();
        icon.GetComponent<MeshRenderer>().material = stopped;
    }

    }