[Unity3D] Unity3D game development: Selecting objects and displaying outlines in 3D scenarios

Source: Internet
Author: User

Hello everyone, I'm Qin Yuanpei. Welcome to follow my blog. My blog address is blog.csdn.net/qinyuanpei.

In games such as legend of the legend. For example, to add a status for our role, increase the volume of blood for our role, and select an enemy to attack, we usually use the mouse to select a target object. When the mouse moves to the target object, the target object displays the contour line, indicating that the current object is selected. On this basis, we can perform a series of operations on the game object. How can this function be implemented in Unity3D? First, we can break down the problem into two subproblems: first, how to determine whether the object is selected; second, how to clearly convey the object to the user after it is selected. It is the battle picture of the Ancient Swordsman and the legend of the legend:



Next, we will solve these two problems respectively. For the first problem, we can take the method of ray detection, that is, from the camera to the position where the mouse is located, if the ray hits an object in the game scenario, we think the object has been selected. For the second question, we need to display the outline of an object, which is an important part of our research today. In Unity3D, we can use the Shader as the shadow to change the material rendering method. Unity3D has six built-in pasters, from simple vertex to complex Parallax pasters with highlights (Parallax Bumped with Specular). There are 30 in total. Where:

1. Normal: applies to opaque objects.

2. Transparent: Suitable for translucent objects. Transparency is determined by the alpha channel of the texture.

3. TransparentCutOut: applicable to some objects that are partially transparent and partially opaque.

4. Self-Illuminated: Applicable to Self-emitting objects

5. Reflective: Suitable for objects that need to reflect ambient light

6. Lightmapped: Applicable to the need to add illumination maps and corresponding UV coordinate values

In a general sense, the shader defines the method for rendering objects, the textures specified in the materials, the vertices and fragment coloring programs used for rendering, the colors adjusted in the materials, and various numerical settings. Correspondingly, the material determines the pasters we will use for rendering and the colors used for rendering. In today's article, we will define the following shadow code:

Shader "Custom/BoundryShader" {Properties {// defines the Material Color as white _ Color ("Main Color", Color) =) // define the material contour to Black _ OutlineColor ("Outline Color", Color) =) // change the color of the contour edge. // define the linewidth _ Outline ("Outline width", Range (0.0, 0.03 )) = 0.001 // change the width of the contour edge _ MainTex ("Base (RGB)", 2D) = "white" {}} CGINCLUDE # include "UnityCG. cginc "struct appdata {float4 vertex: POSITION; float3 normal: NORMAL;}; struct v2f {float4 pos: POSITION; float4 color: COLOR;}; uniform float _ Outline; uniform float4 _ OutlineColor; v2f vert (appdata v) {// just make a copy of incoming vertex data but scaled according to normal directionv2f o; o. pos = mul (UNITY_MATRIX_MVP, v. vertex); float3 norm = mul (float3x3) UNITY_MATRIX_IT_MV, v. normal); float2 offset = TransformViewToProjection (norm. xy); o. pos. xy + = offset * o. pos. z * _ Outline; o. color = _ OutlineColor; return o ;} ENDCGSubShader {Tags {"Queue" = "Transparent"} // note that a vertex shader is specified here but its using the one abovePass {Name "OUTLINE" Tags {"LightMode" =" always "} Cull OffZWrite OffZTest AlwaysColorMask RGB // alpha not used // you can choose what kind of blending mode you want for the outlineBlend SrcAlpha OneMinusSrcAlpha // Normal // Blend One // additive // Blend One partition // Soft Additive // Blend DstColor Zero // Multiplicative // Blend DstColor SrcColor // 2x variant # pragma vertex vert # pragma fragment fraghalf4 frag (v2f I): COLOR {return I. color ;} ENDCG} Pass {Name "BASE" ZWrite OnZTest LEqualBlend SrcAlpha limit {Diffuse [_ Color] Ambient [_ Color]} Lighting OnSetTexture [_ MainTex] {ConstantColor [_ Color] Combine texture * constant} SetTexture [_ MainTex] {Combine previous * primary DOUBLE }}} SubShader {Tags {"Queue" = "Transparent"} Pass {Name "OUTLINE" Tags {"LightMode" = "Always"} Cull FrontZWrite OffZTest AlwaysColorMask RGB // you can choose what kind of blending mode you want for the outlineBlend SrcAlpha restart // Normal // Blend One // Additive // Blend One one runner // Soft Additive // Blend DstColor Zero // Multiplicative // Blend DstColor SrcColor // 2x needed # pragma vertex vert # pragma required gles xbox360 required [_ MainTex] {combine primary} Pass {Name "BASE" ZWrite OnZTest LEqualBlend SrcAlpha limit {Diffuse [_ Color] Ambient [_ Color]} Lighting OnSetTexture [_ MainTex] {ConstantColor [_ Color] Combine texture * constant} SetTexture [_ MainTex] {Combine previous * primary DOUBLE }}} Fallback "Diffuse "}

For the compilation of the colorant program, we can put it aside first. Here we will learn how to use the colorant to achieve different rendering effects. Let's create a new material and set the color palette of this material as the color palette we wrote here,


Well, after the materials are ready, we can officially start the content today. Let's create a simple scenario:


Note that there is no Contour in the object here, because we use the Default material Default-Diffuse. Then, we can change the material dynamically through programming to achieve different rendering effects and write the following script:

Using UnityEngine; using System. collections; public class ShowBoundry: MonoBehaviour {// use the simple Material for displaying the outline public Material mSimpleMat; // use the advanced Material for displaying the outline public Material mAdvanceMat; // default Material public Material mDefaultMat; void Update () {// obtain the mouse position Vector3 mPos = Input. mousePosition; // Ray mRay = Camera. main. screenPointToRay (Input. mousePosition); RaycastHit mHit; // ray test if (Physics. raycast (mRay, out mHit) {// Cube if (mHit. collider. gameObject. tag = "Cube") {// Replace the selected object material with a material mHit with a contour. collider. gameObject. renderer. material = mSimpleMat; // Replace the unselected object material with the default GameObject material. find ("Sphere "). renderer. material = mDefaultMat; // sets the message GameObject. find ("GUIText "). guiText. text = "the selected object is: Cube";} // Sphere if (mHit. collider. gameObject. tag = "Sphere") {// Replace the selected object material with a material mHit with a contour. collider. gameObject. renderer. material = mSimpleMat; // Replace the unselected object material with the default GameObject material. find ("Cube "). renderer. material = mDefaultMat; // sets the message GameObject. find ("GUIText "). guiText. text = "the selected object is: Sphere";} // Person if (mHit. collider. gameObject. tag = "Person") {// This method is unavailable because the material of the character model is complex }}}}

In the above script, we first specify three materials, which are materials with contour lines for simple objects (such as cubes) and are suitable for complex objects (such as character models) material with contour (not implemented in this article), applicable to the default material of Simple objects. The main principle is the ray test method we mentioned at the beginning of this article. We bound this script to an object in a game scenario. After setting the tag, we can run the program. Let's take a look at the effect of the program!


This is what we want to achieve today. Through today's articles, we can select an object in 3D scenarios. There are still many such demands in the game, haha. What should we do for complex character models? The model usually has many textures. If we create a corresponding material file for each texture, isn't it complicated? So please pay attention to my blog and we will announce it in the next article. Good morning!


Daily proverbs: Life is like a mountain. What matters is not its level, but its spirit show.




If you like my blog, please remember my name: Qin Yuanpei. My blog address is blog.csdn.net/qinyuanpei
Reprinted please indicate the source, Author: Qin Yuanpei, the source of this article: http://blog.csdn.net/qinyuanpei/article/details/26435473


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.