Unity&shader Basics-Drawing grids + discs

Source: Internet
Author: User
Tags mul ranges

First, preface

Respect the original, reproduced please specify the source of Kyle eight elder brother column

The previous chapter clicked Open Link has drawn a checkerboard grid, first to improve the shader of this picture grid, add attributes, attributes include the grid line width, grid color and so on. The code is as follows:

Shader "Unlit/chapter2-2" {properties{_backgroundcolor ("Panel background color", color) = (1.0,1.0,1.0,1.0) _axescolor ("Color of Axis", ) = (0.0,0.0,1.0) _gridcolor ("Color of Grid", color) = (0.5,0.5,0.5) _tickwidth ("Intensity of Grid", Range (0.1,1)) =0.1_gridwidth ("width of grid" , Range (0.0001,0.01)) =0.008_axesxwidth ("width of x axis", range (0.0001,0.01)) =0.006_axesywidth ("width of y-axis", range (0.0001,0.01)) =0.007}subshader{//remove occlusion and depth buffer cull offzwrite off//open depth Test ztest alwayscginclude//Add a calculation method float mod (float a,float b) {// The floor (x) method is the CG language built-in method that returns the largest integer less than x return A-b*floor (A/b);} endcgpass{cgprogram//when tapping the code to note: "Cgprogram" and "#pragma ..." in the spelling of different, I do not know what "pragma" is the word #pragma vertex vert#pragma Fragment Frag#include "Unitycg.cginc" uniform float4 _backgroundcolor;uniform float4 _axescolor;uniform float4 _ Gridcolor;uniform float _tickwidth;uniform float _gridwidth;uniform float _axesxwidth;uniform float _axesywidth;struct Appdata{float4 vertex:position;float2 uv:texcoord0;}; struct V2F{FLOAT2 uv:texcoord0;float4 vertex:sv_position;}; v2f Vert (AppData v) {v2f O;o.vertex = Mul (UNity_matrix_mvp,v.vertex); o.uv = V.uv;return o;}  Fixed4 Frag (v2f i): sv_target{//moves the center of the coordinate from the lower-left corner to the center of the grid fixed2 r = 2.0*fixed2 (i.uv.x-0.5,i.uv.y-0.5); Fixed3 backgroundcolor = _backgroundcolor.xyz;fixed3 Axescolor = _axescolor.xyz;fixed3 Gridcolor = _gridcolor.xyz;fixed3 pixel = BackgroundColo r;//defines the width of the mesh const float tickwidth = _tickwidth;if (mod (r.x, tickwidth) < _gridwidth) {pixel = Gridcolor;} if (mod (R.Y, tickwidth) < _gridwidth) {pixel = Gridcolor;} Draw two axes if (ABS (r.x) < _axesxwidth) {pixel = Axescolor;} if (ABS (R.Y) < _axesywidth) {pixel = Axescolor;} Return fixed4 (pixel, 1.0);} ENDCG}}}

Move the pivot of the grid to a central location by using the following code

Fixed2 r = 2.0*fixed2 (i.uv.x-0.5,i.uv.y-0.5);
:


two, draw a disc

Principle: The Circle equation is (x-a) ^2+ (y-b) ^2=r^2, according to the equation can add the following method to calculate the color value information of the predetermined disc

Add a second calculation method to draw disk Fixed3 disk (fixed2 r,fixed2 center,fixed radius,fixed3 color,fixed3 pixel) based on RADIUS, origin, offset r and color of origin, {Fixed3 Col=pixel;if (Length (R-center) < radius) {col = color;} return col;}
Effect:

The complete code is as follows:
Shader "Unlit/chapter3-2" {properties{_backgroundcolor ("Panel background color", color) = (1.0,1.0,1.0,1.0) _col1 ("Color of disc 1", color) = ( 0.216, 0.471, 0.698)//Blue_col2 ("Disc 2 Color", color) = (1.00, 0.329, 0.298)//Red_col3 ("Disk 3 color", color) = (0.867, 0.910, 0.24 7)//YELLOW_CENTER2X ("position of the Origin x of the third disc", Range (0.0,1.0)) = 0.9_center2y ("Position of the Origin y of the third disc", Range (0.0,1.0)) = -0.4_radius1 (" The radius of the first disc ", Range (0.1,1)) = 0.8_radius2 (" Radius of the second disc ", Range (0.1, 1)) = 0.3_RADIUS3 (" Radius of the third disc ", Range (0.1, 1)) = 0.6} subshader{//remove occlusion and depth buffer cull offzwrite off//open depth Test ztest alwayscginclude//Add a calculation method float mod (float a,float b) {//floor (x) method is the CG language built-in method that returns the largest integer less than x return A-b*floor (A/b);} Add a second calculation method to draw disk Fixed3 disk (fixed2 r,fixed2 center,fixed radius,fixed3 color,fixed3 pixel) based on RADIUS, origin, offset r and color of origin, {Fixed3 Col=pixel;if (Length (R-center) < radius) {col = color;} return col;} endcgpass{cgprogram//when tapping the code to note: "Cgprogram" and "#pragma ..." in the spelling of different, I do not know what "pragma" is the word #pragma vertex vert#pragma Fragment Frag#include "Unitycg.cginc" uniform float4 _backgroundcolor;uniform FLOAT4 _col1;uniform float4 _col2;uniform float4 _col3;uniform float _radius1;uniform float _radius2;uniform float _radius 3;uniform float _center2x;uniform float _center2y;struct appdata{float4 vertex:position;float2 uv:TEXCOORD0;}; struct V2F{FLOAT2 uv:texcoord0;float4 vertex:sv_position;}; v2f Vert (AppData v) {v2f O;o.vertex = Mul (Unity_matrix_mvp,v.vertex); o.uv = V.uv;return o;} Fixed4 Frag (v2f i): sv_target{float2 r = 2.0* (i.uv-0.5); float aspectratio = _screenparams.x/_screenparams.y;r.x *= ASP Ectratio;fixed3 BackgroundColor = _backgroundcolor.xyz;fixed3 col1 = _col1.xyz;fixed3 col2 = _col2.xyz;fixed3 col3 = _col3 . xyz;fixed3 pixel = _backgroundcolor;//Draw the first disc pixel = Disk (R,fixed2 (0.1,0.3), _radius1,col3,pixel);//Draw a second disc pixel= disk (R, Fixed2 (_CENTER2X, _center2y), _radius2, col2, pixel);//Draw a third disc pixel= disk (R, Fixed2 ( -0.8, 0.6), _RADIUS3, col1, pixel) ; return fixed4 (Pixel, 1.0);} ENDCG}}}
Third, draw the disc in the grid1, according to the principle of drawing a disk in 2, as long as A and b through C # code to pass parameters to shader to control, this parameter is the mouse click on the coordinates of the position. Of course, this position is calculated to be applied to grid coordinates, and the grid coordinates are -1~1 and converted by code:
void Update () {        if (input.getmousebuttondown (0))        {            vec_mousebtnpos = input.mouseposition;            Divide the position of the mouse by the screen parameter to get a range of coordinate ranges of 0~1            vec_mousebtnpos = new Vector2 (vec_mousebtnpos.x/screen.width, VEC_MOUSEBTNPOS.Y/ Screen.height);            Set coordinate origin to midpoint            vec_mousebtnpos-= new Vector2 (0.5f,0.5f);            Vec_mousebtnpos *= 2;            Vec_mousebtnpos.y =-vec_mousebtnpos.y;}
Basically the same method as the shader code, get:2, the point is fixed at the intersection point of the gridsee here, everybody crossing you will think I want to do what? Haha, yes is a gobang, with shader to write a Gobang, think are very excited. OK, back to the point, with the foundation of the previous step, now we just need to make a judgment between the mouse click Points and the nearby grid intersection, to see if the threshold is reached, if so, let the red dot fixed draw at this intersection. The complete code is as follows:
Using unityengine;using system.collections;using system.collections.generic;///<summary>///This script implements the effect of clicking on a single point    </summary>public class Gamecontrol:monobehaviour {public Material mat;    The minimum error in the set point is public float clickminerror;    The coordinate set of the grid point private list<vector2> List_gridintersectionpos = new list<vector2> ();    The number of grid points is private int gridintersectionnums;    private float Gridspace;    Private Vector2 Vec_mousebtnpos; Use the this for initialization void Start () {gridspace = Mat.        GetFloat ("_tickwidth"); The number of grid points on a single axis is equal to the horizontal coordinate spacing divided by the grid spacing gridintersectionnums = (int) mathf.floor (1.0f/gridspace); This cannot be used only with coercion type conversions, if the use of coercion type conversion will lose data, such as 1.0/0.1 the final result is 9 for (int i =-gridintersectionnums; I <= gridintersectionnums; i            + +) {float x = gridspace * i; for (int j =-gridintersectionnums; J <= Gridintersectionnums; j + +) {Float y = gridspace * j                ; List_gridintersecTionpos.add (New Vector2 (x, y));            }}}//update is called once per framevoid update () {if (Input.getmousebuttondown (0)) {            Vec_mousebtnpos = input.mouseposition;  Divide the position of the mouse by the screen parameter to get a range of coordinate ranges of 0~1 Vec_mousebtnpos = new Vector2 (vec_mousebtnpos.x/screen.width, VEC_MOUSEBTNPOS.Y/            Screen.height);            Set coordinate origin to midpoint vec_mousebtnpos-= new Vector2 (0.5f,0.5f);            Vec_mousebtnpos *= 2;          Vec_mousebtnpos.y =-vec_mousebtnpos.y; /* Mat.            SetFloat ("_mousebtnposx", vec_mousebtnpos.x); Mat. SetFloat ("_mousebtnposy", vec_mousebtnpos.y); *//If the dot is in the intersection of the grid, the dot int index = Checkclikedint               Ersection (Vec_mousebtnpos); if (Index! =-1) {//assigns the location of the exact grid point to vec_mousebtnpos vec_mousebtnpos = List                   _gridintersectionpos[index]; Mat.                   SetFloat ("_mousebtnposx", vec_mousebtnpos.x); Mat.                 SetFloat ("_mousebtnposy", vec_mousebtnpos.y);        } Debug.Log ("x:" + vec_mousebtnpos.x + "y:" + vec_mousebtnpos.y); }}///<summary>///Determine if the place in the mouse point is at the intersection of the grid///</summary>//<param name= "VEC2" ></param&gt    ;        <returns></returns> private int checkclikedintersection (Vector2 vec2) {int clickindex =-1; for (int i = 0; i < List_gridintersectionpos.count; i++) {Float Errorx = mathf.abs (vec2.x-li            st_gridintersectionpos[i].x);            float errory = Mathf.abs (VEC2.Y-LIST_GRIDINTERSECTIONPOS[I].Y);            If the value of the error is less than the preset value, the float error = mathf.sqrt (Errorx * Errorx + errory * errory) is awarded in the fixed point;                if (error<clickminerror) {clickindex = i;            Break    }} return clickindex; }}
here the "Checkclikedintersection" method is used for judging and correcting, and a minimum error "Clickminerror" is set. :3, the complete shader code is as follows:
Shader "Unlit/backgammon" {properties{_backgroundcolor ("Panel background color", color) = (1.0,1.0,1.0,1.0) _axescolor ("Color of Axis", ) = (0.0,0.0,1.0) _gridcolor ("Color of Grid", color) = (0.5,0.5,0.5) _tickwidth (spacing of grid, Range (0.1,1)) = 0.1_gridwidth ("width of grid", Range (0.0001,0.01) = 0.008_axesxwidth ("width of x-axis", range (0.0001,0.01)) = 0.006_axesywidth ("width of y-axis", range (0.0001,0.01)) = 0.007_MOUSEBTNPOSX ("Mouse-click X-Direction position", float) = 0.0_mousebtnposy ("Mouse-click y-Direction position", float) = 0.0_mousebtnradius ("radius of the position disc in the mouse point", float) = 0.001_mousedowncolor ("Color in mouse point", color) = (1.00, 0.329, 0.298,1.0)}subshader{//remove occlusion and depth buffer cull offzwrite off// Open depth Test ztest alwayscginclude//Add a calculation method float mod (float a,float b) {//floor (x) method is the CG language built-in method that returns the largest integer less than x return A-b*floor ( A/b);} Add a second calculation method, based on the radius, origin and color to draw disk Fixed3 disk (fixed2 r,fixed2 center,fixed radius,fixed3 color,fixed3 pixel) {fixed3 col = Pixel;if (Length (R-center) < radius) {col = color;} return col;} endcgpass{cgprogram//when tapping the code to note: "Cgprogram" and "#pragma ..." in the spelling of different, I do not know what "pragma" is the word #pragma vertex vert#pragma Fragment Frag#iNclude "Unitycg.cginc" uniform float4 _backgroundcolor;uniform float4 _axescolor;uniform float4 _gridcolor;uniform Float _tickwidth;uniform float _gridwidth;uniform float _axesxwidth;uniform float _axesywidth;uniform float _ Mousebtnposx;uniform float _mousebtnposy;uniform float _mousebtnradius;uniform float4 _mousedowncolor;struct appdata{ Float4 vertex:position;float2 uv:texcoord0;}; struct V2F{FLOAT2 uv:texcoord0;float4 vertex:sv_position;}; v2f Vert (AppData v) {v2f O;o.vertex = Mul (Unity_matrix_mvp,v.vertex); o.uv = V.uv;return o;} Fixed4 Frag (v2f i): sv_target{//moves the center of the coordinate from the lower-left corner to the center of the grid float2 r = 2.0* (i.uv-0.5); float aspectratio = _screenparams.x/_scree Nparams.y;//r.x *= aspectratio;fixed3 backgroundcolor = _backgroundcolor.xyz;fixed3 AxesColor = _axesColor.xyz;fixed3 Gridcolor = _gridcolor.xyz;fixed3 pixel = backgroundcolor;//defines the spacing of the mesh const float tickwidth = _tickwidth;if (mod (r.x, tickw Idth) < _gridwidth) {pixel = Gridcolor;} if (mod (R.Y, tickwidth) < _gridwidth) {pixel = Gridcolor;} DrawTwo axes if (ABS (r.x) < _axesxwidth) {pixel = Axescolor;} if (ABS (R.Y) < _axesywidth) {pixel = Axescolor;} Draw a point pixel = Disk (R, Fixed2 (_mousebtnposx, _mousebtnposy), _mousebtnradius, _mousedowncolor, pixel); return fixed4 ( Pixel, 1.0);} ENDCG}}}
The code adds a location to receive the mouse clicks passed by the C # script"uniform float _mousebtnposx;uniform float_mousebtnposy;" In This step, it is not possible to make a complete gobang, because now you can draw only one point, and of course you could draw multiple points by adding code to the shader code, but it does not reach our ideal condition. The next section will give you a technique to implement how C # scripts can pass arrays to shader to implement shader code to draw multiple points. attached to this section of the project Baidu Network disk project, using the Unity5.3.3 version



Unity&shader Basics-Drawing grids + discs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.