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

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

    }

Thursday, 29 November 2018

Getting Timestamp in Unity C#

Create two 3DText mesh in unity and create a empty game object and attach the below script.

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

public class TimeStampHandler : MonoBehaviour
{
    public TextMesh dateText, timeText;

    // Use this for initialization
    void Start () {

}

    void Update()
    {
        //string currDay = System.DayOfWeek;
        string currDate = System.DateTime.Now.ToString("yyyy/MM/dd ").ToString();
        string currTime = System.DateTime.Now.ToString("HH:mm:ss").ToString();
        dateText.text = System.DateTime.Now.DayOfWeek.ToString() + " " + currDate;
        timeText.text = currTime;
    }
}

Tuesday, 13 November 2018

Atmosphere Shader in Unity

Shader "Custom/Atmosphere" {
Properties{
_Color("Color", Color) = (1,1,1,1)
_Size("Atmosphere Size Multiplier", Range(0,16)) = 4
_Rim("Fade Power", Range(0,8)) = 4
_Light("Lighting Power", Range(0,10)) = 1.4
_Ambient("Ambient Power", Range(0,6)) = 0.8

}
SubShader{
Tags{ "RenderType" = "Transparent" }
LOD 200

Cull Front

CGPROGRAM
// Physically based Standard lighting model, and enable shadows on all light types
#pragma surface surf NegativeLambert fullforwardshadows alpha:fade
#pragma vertex vert

// Use shader model 3.0 target, to get nicer looking lighting
#pragma target 3.0


struct Input {
float3 viewDir;
};

half _Size;
half _Rim;
half _Light;
half _Ambient;
fixed4 _Color;

void vert(inout appdata_full v) {
v.vertex.xyz += v.vertex.xyz * _Size / 10;
v.normal *= -1;
}

half4 LightingNegativeLambert(SurfaceOutput s, half3 lightDir, half3 viewDir, half atten) {
s.Normal = normalize(s.Normal);

half diff = max(0, dot(-s.Normal, lightDir)) * _Light + _Ambient;

half4 c;
c.rgb = (s.Albedo * _LightColor0 * diff) * atten;
c.a = s.Alpha;
return c;
}

void surf(Input IN, inout SurfaceOutput o) {
half rim = saturate(dot(normalize(IN.viewDir), o.Normal));

// Albedo comes from a texture tinted by color
fixed4 c = _Color;
o.Albedo = c.rgb;
o.Alpha = lerp(0, 1, pow(rim, _Rim));
}
ENDCG
}
FallBack "Diffuse"
}

Monday, 12 November 2018

Gradient Shader in Unity

// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'

Shader "Custom/gradient" {
Properties
{
_TopColor("Top Color", Color) = (1, 1, 1, 1)
_BottomColor("Bottom Color", Color) = (1, 1, 1, 1)
_RampTex("Ramp Texture", 2D) = "white" {}
}
SubShader
{
Pass
{
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
struct vertexIn {
float4 pos : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f {
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
};
v2f vert(vertexIn input)
{
v2f output;
output.pos = UnityObjectToClipPos(input.pos);
output.uv = input.uv;
return output;
}
fixed4 _TopColor, _BottomColor;
sampler2D _RampTex;
fixed4 frag(v2f input) : COLOR
{
return lerp(_BottomColor, _TopColor, input.uv.x);
}
ENDCG
}
}
}

Back Face Culling shader in Unity

Shader "Custom/backFaceChecker" {
Properties{
_Color("Main Color", Color) = (1,1,1,1)
_SpecColor("Specular Color", Color) = (0.5, 0.5, 0.5, 0)
_Shininess("Shininess", Range(0.01, 1)) = 0.078125
_MainTex("Base (RGB) TransGloss (A)", 2D) = "white" {}
_BumpMap("Normalmap", 2D) = "bump" {}
_Cutoff("Alpha cutoff", Range(0,1)) = 0.5
}

SubShader{
Cull Off
Tags{ "Queue" = "AlphaTest" "IgnoreProjector" = "True" "RenderType" = "TransparentCutout" }
LOD 400

CGPROGRAM
#pragma surface surf BlinnPhong alphatest:_Cutoff
#pragma exclude_renderers flash

sampler2D _MainTex;
sampler2D _BumpMap;
fixed4 _Color;
half _Shininess;

struct Input {
float2 uv_MainTex;
float2 uv_BumpMap;
};

void surf(Input IN, inout SurfaceOutput o) {
fixed4 tex = tex2D(_MainTex, IN.uv_MainTex);
o.Albedo = tex.rgb * _Color.rgb;
o.Gloss = tex.a;
o.Alpha = tex.a * _Color.a;
o.Specular = _Shininess;
o.Normal = UnpackNormal(tex2D(_BumpMap, IN.uv_BumpMap));
}
ENDCG
}

FallBack "Transparent/Cutout/VertexLit"
}

Creating x-ray shader in Unity

// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'

Shader "Custom/xrayMode" {
Properties{
_Color("_Color", Color) = (0,1,0,1)
_Inside("_Inside", Range(0,1)) = 0
_Rim("_Rim", Range(0,2)) = 1.2
}
SubShader{
Tags{ "Queue" = "Transparent" }
LOD 80

Pass{
Name "Darken"
Cull off
Zwrite off
Blend dstcolor zero

CGPROGRAM

#pragma vertex vert_surf
#pragma fragment frag_surf
#pragma fragmentoption ARB_precision_hint_fastest
//#pragma multi_compile_fwdbase

#include "HLSLSupport.cginc"
#include "UnityCG.cginc"


struct v2f_surf {
half4 pos : SV_POSITION;
fixed4 finalColor : COLOR;
};

uniform half4 _Color;
uniform half _Rim;
uniform half _Inside;

v2f_surf vert_surf(appdata_base v) {
v2f_surf o;

o.pos = UnityObjectToClipPos(v.vertex);
half3 uv = mul((float3x3)UNITY_MATRIX_IT_MV, v.normal);
uv = normalize(uv);
o.finalColor = lerp(half4(1,1,1,1),_Color,saturate(max(1 - pow(uv.z,_Rim),_Inside)));
return o;
}

fixed4 frag_surf(v2f_surf IN) : COLOR{

return IN.finalColor;
}

ENDCG
}

Pass{
Name "Lighten"
Cull off
Zwrite off
Blend oneminusdstcolor one

CGPROGRAM

#pragma vertex vert_surf
#pragma fragment frag_surf
#pragma fragmentoption ARB_precision_hint_fastest
//#pragma multi_compile_fwdbase

#include "HLSLSupport.cginc"
#include "UnityCG.cginc"


struct v2f_surf {
half4 pos : SV_POSITION;
fixed4 finalColor : COLOR;
};

uniform half4 _Color;
uniform half _Rim;
uniform half _Inside;

v2f_surf vert_surf(appdata_base v) {
v2f_surf o;

o.pos = UnityObjectToClipPos(v.vertex);
half3 uv = mul((float3x3)UNITY_MATRIX_IT_MV, v.normal);
uv = normalize(uv);
o.finalColor = lerp(half4(0,0,0,0),_Color,saturate(max(1 - pow(uv.z,_Rim),_Inside)));
return o;
}

fixed4 frag_surf(v2f_surf IN) : COLOR{

return IN.finalColor;
}

ENDCG
}
}

FallBack "Mobile/VertexLit"
}

Thursday, 6 September 2018

Creating a Splash Screen and Menu Screen in Libgdx and Android Studio

Creating Splash Screen and Menu Screen with Libgdx and Android Studio


If you not aware of creating a new project using libgdx and android studio please visit this page to get started http://sharewhatulearn.blogspot.com/2018/09/getting-started-with-libgdx-android.html

Once you have opened the created project in Android Studio you can find the Test Class under Core -> Java-> com.test.game this call will act as the main Game class which will call other screens.

**I have renamed the Test class as GamePlay you can do this by right clicking on the class and do a Refactor-> Rename

Under this Class GamePlay paste the below code you can find the comments for the code inline


------------------------------------------------------------------
package com.test.game;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;

public class GamePlay extends Game {

    // one for each possible screen    public static final int SPLASH_SCREEN = 0;
    public static final int GAME_SCREEN = 1;
    public static final int GAME_PLAY = 2;
    public static final int GAME_OVER_SCREEN = 3;

    public GamePlay() { super(); }

    @Override    public void create ()
    {
        changeScreen(SPLASH_SCREEN);
// Dy default the splash screen will be loaded once the game is launched    }

    @Override    public void dispose()
    {
        // DISPOSE ALL RESOURCES        getScreen().dispose();
        Gdx.app.exit();
    }
//This function will be called from other screen classes to swith the screen    public void changeScreen(int screen)
    {
        if(screen == SPLASH_SCREEN){
            this.setScreen(new SplashScreen(this));
        }else if(screen == GAME_SCREEN){
            this.setScreen(new MenuScreen(this));
        }else if(screen == GAME_PLAY){
            this.setScreen(new CorePlay(this));
        }
    }
}
---------------------------------------------------------------------------------

Okay now let us create a splash screen to do this we need to create a new class you can
do this by right clicking on the com.test.game under projects window.

In splash screen we are just going to load a Bg Image these images needs to be copied 
to the assets folder under the project\android\assets

Now open the newly created SplashScreen class and paste the below code
-------------------------------------------------------------------------------------------------------------
package com.test.game;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.TimeUtils;


public class SplashScreen implements Screen {
    private SpriteBatch batch;
    private Texture ttrSplash;
    private GamePlay parent;

    private float timeToShowSplashScreen = 2f; // 2 seconds
    // pass the parent game to this screen so this screen can tell the parent its finished    // and tell it to load the next screen    public SplashScreen(GamePlay p) {
        super();
        parent = p;
        batch = new SpriteBatch();
        ttrSplash = new Texture("loginbg-01.png");
    }

    @Override    public void render(float delta) {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.begin();
        batch.draw(ttrSplash, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        batch.end();

        timeToShowSplashScreen -= delta; // remove delta from time        if(timeToShowSplashScreen <= 0){ // 2 seconds are up            // tell parent to change screen            parent.changeScreen(GamePlay.GAME_SCREEN);
        }
    }

    @Override    public void hide() { }

    @Override    public void pause() { }

    @Override    public void resume() { }

    @Override    public void show() { }

    @Override    public void resize(int width, int height) { }

    @Override    public void dispose() {
        ttrSplash.dispose();
        batch.dispose();
    }
}
-------------------------------------------------------------------------------------------------------------
Now its time to create the Menu screen to do this repeat the same process which we followed
to create the SplashScreen class. I have created the new main menu screen as MenuScreen 
class.

Once you are done with class creation use the below code. 
This code adds a bg image, creates 2 button and and adds event listener to the button.
Later we will use this event listener to trigger to call to core game play screen.

For the buttons I have used the Libgdx free button skins you can download it from here
https://github.com/czyzby/gdx-skins

The downloaded skin too needs to be placed under assets folder
-------------------------------------------------------------------------------------------------------------
package com.test.game;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;

public class MenuScreen implements Screen {

    private final Stage stage;
    Texture sceneBg;
    private SpriteBatch batch;
    Game game;
    private GamePlay parent;

    public MenuScreen(GamePlay p) {
        super();
        parent = p;

        stage = new Stage();
        Gdx.input.setInputProcessor(stage);

        sceneBg = new Texture("loginbg-01.png");
        batch = new SpriteBatch();

        Skin mySkin = new Skin(Gdx.files.internal("skin/glassy-ui.json"));
        TextButton fbButton = new TextButton("Facebook Login", mySkin);
        fbButton.setWidth(600.0f);
        fbButton.setPosition((stage.getWidth()/2)-fbButton.getWidth()/2, stage.getHeight()/2);


        TextButton guestButton = new TextButton("Guest Login", mySkin);
        guestButton.setWidth(600.0f);
        guestButton.setPosition((stage.getWidth()/2) - guestButton.getWidth()/2, fbButton.getY()- (fbButton.getHeight()+30.0f));

        fbButton.addListener(new ClickListener()
        {
           //game.setScreen(new GamePlay(game));        });
        guestButton.addListener(new ClickListener()
        {
            @Override            public void clicked(InputEvent event, float x, float y) {
                parent.changeScreen(GamePlay.GAME_PLAY);
            };
        });

        stage.addActor(fbButton);
        stage.addActor(guestButton);
    }

    @Override    public void show() { }

    @Override    public void render(float delta) {
        stage.act(delta);

        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.begin();
        batch.draw(sceneBg, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        batch.end();

        stage.draw();
    }

    @Override    public void resize(int width, int height) { }

    @Override    public void pause() { }

    @Override    public void resume() { }

    @Override    public void hide() { }

    @Override    public void dispose() { }
}
-------------------------------------------------------------------------------------------------------------

Now it time to create the new class which will be called when 
the button is triggered from the menu screen.
We are going to follow the same process as we did before for creating splash screen
and MenuScreen.
I have named this class as CorePlay.
Once you have created paste the below code in this class.

-------------------------------------------------------------------------------------------------------------
package com.test.game;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Stage;

public class CorePlay implements Screen
{
    Stage stage;
    private GamePlay parent;
    Texture sceneBg;
    private SpriteBatch batch;

    public CorePlay(GamePlay p)
    {
        super();
        parent = p;
        stage = new Stage();
        Gdx.input.setInputProcessor(stage);

        sceneBg = new Texture("mainScreenBG-01-01.png");
        batch = new SpriteBatch();

    }
    @Override    public void show()
    {

    }
    @Override    public void render(float delta) {
        stage.act(delta);

        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.begin();
        batch.draw(sceneBg, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        batch.end();

        stage.draw();
    }

    @Override    public void resize(int width, int height) { }

    @Override    public void pause() { }

    @Override    public void resume() { }

    @Override    public void hide() { }

    @Override    public void dispose() { }
}

-------------------------------------------------------------------------------------------------------------

That's it now go to Run and Run Android in the editor you will be able to see the
splash screen which is launched and appears for 2 seconds and then the menu screen 
and upon clicking the Guest Login button you will be taken to the next screen.


Wednesday, 5 September 2018

Getting started with Libgdx & Android Studio



Getting started with Libgdx & Android Studio

  1. Before getting started with libgdx install Android studio and configure with required tools and API.
  2. Download Libgdx from this link https://libgdx.badlogicgames.com/download.html
  3. Run gdx-setup executable Jar file and you will get a window as below.
  4. Enter the details and browse the destination and Android SDK path.
  5. Select the sun project type as per your need here I am going to develop for Android and IOS 
  6. Under extension keep Box2d selected
  7. Click on Generate
  8. Navigate to the destination path to ensure project is created.
  9. Launch android studio and click on import project and navigate to the destination where we created the project and launch it.
  10. In android studio go to Tool AVD Mananger and launch a virtual device
  11. Now go to Run and click on Run Android to run the project on virtual device. You should get a screen as below in the virtual emulator.

Android Studio 3.4.1 fixing Execution failed for task ':android:validateSigningDebug'.

This Error normally happens due to misplacement of Key or unavailability of Key which is required to publish .APK to solve this issue follow the below steps.

1. In android studio go to Build-> Generate signed APK
2. Choose create new and select a path to save the file enter the details and remember the Key Alias and password that you enter we will be using this later.

3. Now select the recently created key on the Generate signed APK window.
4. Go to project and select Android right click -> Open Module Setting
5. Select Android under Modules and go to signing tab
6. Give a name and enter the details from step 2 and select the generated key file.
7. No move to build types tab and under debug and release select the config which we created on previous step 7 for Signing config.

8.That's it now clean you project and build it.