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.

Monday, 3 September 2018

Cocos Creator – Creating a video player

  1. Create a new scene
  2. Right click on the main camera and create a node with video player under create UI nodes
  3. Similarly create a node with button under create UI nodes
  4. Rename the button and label as show in the below image1
  5. Import a demo video in .mp4 format
  6. Select the video player node under the main camera on Node tree and under the video player option of video player node change the resource type to local.
  7. Now drag the imported video from assets to Clip under video player.
  8. Create a new Js file called as PlayerController.js and copy the below code to it
  9. cc.Class({
    extends: cc.Component,properties: {
    videoPlayer: {
    default: null,
    type: cc.VideoPlayer
    },playBtn:{
    default: null,
    type: cc.Node
    },
    pauseBtn:{
    default: null,
    type: cc.Node
    },
    stopBtn:{
    default: null,
    type: cc.Node
    },
},
start()
{
},
play ()
{
this.videoPlayer.play();
},
pause () {
this.videoPlayer.pause();
},
toggleFullscreen () {
if (
cc.sys.isBrowser &&
cc.sys.browserType === cc.sys.BROWSER_TYPE_MOBILE_QQ &&
cc.sys.browserVersion <= 7.2 &&
/Nexus 6/.test(navigator.userAgent)
) {
// this.tips.textKey = ‘cases/02_ui/09_videoplayer/videoPlayer.nonsupport_fullscreen’;
return cc.log(‘May be crash, so prohibit full screen’);
}
this.videoPlayer.isFullscreen = true;
},
stop () {
this.videoPlayer.stop();
},
keepRatioSwitch () {
this.videoPlayer.keepAspectRatio = !this.videoPlayer.keepAspectRatio;
},
getStatus (event) {
switch (event) {
case cc.VideoPlayer.EventType.PLAYING:
return ‘PLAYING’;
case cc.VideoPlayer.EventType.PAUSED:
return ‘PAUSED’;
case cc.VideoPlayer.EventType.STOPPED:
return ‘STOPPED’;
case cc.VideoPlayer.EventType.COMPLETED:
return ‘COMPLETED’;
case cc.VideoPlayer.EventType.META_LOADED:
return ‘META_LOADED’;
case cc.VideoPlayer.EventType.CLICKED:
return ‘CLICKED’;
case cc.VideoPlayer.EventType.READY_TO_PLAY:
return ‘READY_TO_PLAY’;
default:
return ‘NONE’;
}
},
onVideoPlayerEvent (sender, event)
{
// this.statusLabel.string = this.getStatus(event);
if (event === cc.VideoPlayer.EventType.META_LOADED)
{
var duration = this.videoPlayer.getDuration();
if (duration) {
// this.totalTime.string = duration.toFixed(2);
}
else {
//this.totalTime.string = 0;
}
}
else if (event === cc.VideoPlayer.EventType.CLICKED)
{
if (this.videoPlayer.isPlaying())
{
this.videoPlayer.pause();
} else {
this.videoPlayer.play();
}
}
},
toggleVisibility () {
this.videoPlayer.enabled = !this.videoPlayer.enabled;
},
playOnlineVideo () {
this.videoPlayer.resourceType = cc.VideoPlayer.ResourceType.REMOTE;
this.videoPlayer.remoteURL = ‘http://benchmark.cocos2d-x.org/cocosvideo.mp4&#8217;;
this.videoPlayer.play();
},
playLocalVideo () {
this.videoPlayer.resourceType = cc.VideoPlayer.ResourceType.LOCAL;
this.videoPlayer.play();
},
update () {
if (this.currentTime && this.videoPlayer.currentTime) {
this.currentTime.string = this.videoPlayer.currentTime.toFixed(2);
}
},
});
10. Create an empty node under Node tree as VideoPlayerCtrl
11. Attach the imported script on the VideoPlayerCtrl node by just dragging over the script onto the properties of created node.
12. Now select the VideoPlayerCtrl node and under properties assign the node from node tree by dragging as show in the below pic.
2
13. Now select the play button and add a click event and then under the click event drag and drop the VideoPlayerCtrl node and then under the first drop down select the playerController and under the second drop down select the play method.
3
14. Similarly repeat the steps for stop and pause button and select playerController on first drop down and stop and pause methods respectively on the second drop downs.
15. That’s it.
4