[Unity3D daily development] The effect of arrow pointing to the target point in Unity3D

Recommended reading

Hello everyone, I'm a Buddhist engineer ☆Quiet little magic dragon☆ . I update Unity development skills from time to time. If you find it useful, remember to click three times.

I. Introduction

When I was developing recently, I encountered the need for arrow pointing. I originally wanted to use the code in this article:
[Unity3D daily development] Implementing the arrow pointing effect in Unity

But I thought that this code is running in Update, which has a great impact on efficiency. I just saw this classmate leave me a message:

insert image description here
I took a look at his implementation through Shader and MeshRenderer, and the efficiency should be better. But the steps of the article are a bit simple for me, and I may not know how to use it, so I will subdivide its content.

Effect picture:
insert image description here

Original link: http://www.devacg.com/?post=1415
Author: Chasing the Wind Sword Love
First published on: Personal blog http://www.devacg.com/

2. Text

2-1. Make Shader

(1) First, import our image:
insert image description here
right-click and save as, save it to the project.

(2) Create a new Shader and select in the Project view to Create→Shader→Standard Surface Shader
insert image description here
copy and paste the code into it:

Shader "Custom/NavPathArrow"
{
    
    
    Properties
    {
    
    
        _MainTex("Texture", 2D) = "white" {
    
    }
        _ScrollYSpeed("Y Scroll Speed", Range(-20, 20)) = 2
    }
        SubShader
        {
    
    
            Tags {
    
     "Queue" = "Transparent" "RenderType" = "Transparent" }
            LOD 100
            //双面渲染
            Cull Off
            //Alpha混合
            Blend SrcAlpha OneMinusSrcAlpha

            Pass
            {
    
    
                CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag

                #include "UnityCG.cginc"

                struct appdata
                {
    
    
                    float4 vertex : POSITION;
                    float2 uv : TEXCOORD0;
                };

                struct v2f
                {
    
    
                    float2 uv : TEXCOORD0;
                    float4 vertex : SV_POSITION;
                };

                sampler2D _MainTex;
                float4 _MainTex_ST;
                fixed _ScrollYSpeed;

                v2f vert(appdata v)
                {
    
    
                    v2f o;
                    o.vertex = UnityObjectToClipPos(v.vertex);
                    o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                    return o;
                }

                fixed4 frag(v2f i) : SV_Target
                {
    
    
                    fixed2 uv = i.uv;
                    uv.y += _ScrollYSpeed * _Time;
                    fixed4 col = tex2D(_MainTex, uv);
                    return col;
                }
                ENDCG
            }
        }
}

2-2. Making a shader

Create a new shader, select it in the Project view Create→Material, name it NavPathArrow:
insert image description here
Set the properties of the shader, set the Shader to Custom/NavPathArrow, and drag the texture into it:
insert image description here

2-3. Making prefabs

(1) Create a new Quad object, in the Hierarchy view, right-click and select Create→Quad:

insert image description here
Replace its shader with the shader we just made:
insert image description here
drag it to the Project view to make a prefab:
insert image description here

2-4. Implementation code

Create a new script NavPathArrow.cs, double-click to open the script, and write the code:

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

/// <summary>
/// 导航箭头
/// </summary>
public class NavPathArrow : MonoBehaviour
{
    
    
    public MeshRenderer meshRenderer;//箭头3D对象Quad
    public List<Transform> points = new List<Transform>();//路径点
    private List<MeshRenderer> lines = new List<MeshRenderer>();//显示的路径

    public float xscale = 1f;//缩放比例
    public float yscale = 1f;

    void Start()
    {
    
    
        //箭头宽度缩放值
        xscale = meshRenderer.transform.localScale.x;
        //箭头长度缩放值
        yscale = meshRenderer.transform.localScale.y;
    }

    //画路径
    public void DrawPath()
    {
    
    
        if (points == null || points.Count <= 1)
            return;
        for (int i = 0; i < points.Count - 1; i++)
        {
    
    
            DrawLine(points[i].position, points[i + 1].position, i);
        }
    }

    //画路径 参数为路径点数组
    public void DrawPath(Vector3[] points)
    {
    
    
        if (points == null || points.Length <= 1)
            return;
        for (int i = 0; i < points.Length - 1; i++)
        {
    
    
            DrawLine(points[i], points[i + 1], i);
        }
    }

    //隐藏路径
    public void HidePath()
    {
    
    
        for (int i = 0; i < lines.Count; i++)
            lines[i].gameObject.SetActive(false);
    }

    //画路径
    private void DrawLine(Vector3 start, Vector3 end, int index)
    {
    
    
        Debug.Log(transform.gameObject.name);
        MeshRenderer mr;
        if (index >= lines.Count)
        {
    
    
            mr = Instantiate(meshRenderer);
            lines.Add(mr);
        }
        else
        {
    
    
            mr = lines[index];
        }

        var tran = mr.transform;
        var length = Vector3.Distance(start, end);
        tran.localScale = new Vector3(xscale, length, 1);
        tran.position = (start + end) / 2;
        //指向end
        tran.LookAt(end);
        //旋转偏移
        tran.Rotate(90, 0, 0);
        mr.material.mainTextureScale = new Vector2(1, length * yscale);
        mr.gameObject.SetActive(true);
    }

    void OnGUI()
    {
    
    
        if (GUI.Button(new Rect(20, 40, 80, 20), "显示路径"))
        {
    
    
            DrawPath();
        }
        if (GUI.Button(new Rect(20, 80, 80, 20), "隐藏路径"))
        {
    
    
            HidePath();
        }
    }
}

2-5. Implement functions

Create three new Cubes as path points, one Plane as the floor, and use the command to align the camera directly Ctrl+Shift+Fto the window:
insert image description here
attach the script to the Plane, then drag the path points, which are three Cubes, and then drag the prefab Quad into it:
insert image description here
run the program:
insert image description here

3. Postscript

Your likes are your support for bloggers. If you have any questions, remember to leave a message:
insert image description here

The blogger also has many treasure articles waiting for you to discover:

column direction Introduction
Unity3D develops small games Small game development tutorial Share some small games developed using the Unity3D engine, and share some tutorials for making small games.
Unity3D from entry to advanced getting Started Get inspiration from self-study Unity, summarize the route of learning Unity from scratch, with knowledge of C# and Unity.
Unity 3D yuki UGUI UGUI Unity's UI system UGUI is fully analyzed, starting from the basic controls of UGUI, and then comprehensively teaching the principles of UGUI and the use of UGUI.
Unity3D read data file read Use Unity3D to read txt documents, json documents, xml documents, csv documents, and Excel documents.
Unity3D data collection Data collection Array collection: Knowledge sharing of data collections such as arrays, Lists, dictionaries, stacks, linked lists, etc.
VR/AR (Virtual Simulation) Development of Unity3D virtual reality Summarize the common virtual simulation requirements of bloggers' work for case explanation.
Plugin for Unity3D plugin Mainly share some plug-in usage methods used in Unity development, plug-in introduction, etc.
Daily development of Unity3D daily record Mainly used by bloggers in daily development, methods and skills used, development ideas, code sharing, etc.
Daily BUG of Unity3D daily record Record the bugs and pits encountered in the process of developing projects with the Unity3D editor, so that later people can refer to them.

Guess you like

Origin blog.csdn.net/q764424567/article/details/123811819