前言
众所周知,2016年对“陰陽師”而言是不一样的一年。作为网易在第三季度推出的新游,创新地将原汁原味的和风美学体验带给用户,获得了超出预期的市场反应。9月2日首发当天即获App Store编辑选荐,更在12月发布的App Annie中国区2016年度十佳游戏中占据一席之地。10月初,其中文版在全球多个国家的苹果应用商店上架,根据11月11日首部资料片上线时的App Annie数据,《阴阳师》获得极具突破的瞩目和成绩:中国免费榜第1、畅销榜第1,加拿大畅销榜第1,澳大利亚畅销榜第1,新西兰畅销榜第1,英国畅销榜第8,美国畅销榜第10等等傲人的成绩。
作为其中的核心玩法-画符,是其受到众多玩家青睐的重大原因。
本篇将告诉你怎么在Unity3D中怎么实现这一效果。
思路?
如何实现在屏幕上画东西?
- Unity内置的LineRenderer
- Shader
- 这里我们选择用OpenGL来实现。
在官方帮助文档里面,我们可以找到GL这个API。
代码实现
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
public void GenerateText()
{
Texture2D tmpTex = new Texture2D(300,400);
for (int i = 1; i < allPoints.Count; i++)
{
Vector2 tmpFront = allPoints[i - 1];
Vector2 tmpBack = allPoints[i];
for (int j = 1; j < 100; j++)
{
int xx = (int)(Mathf.Lerp(tmpFront.x * tmpTex.width, tmpBack.x*tmpTex.width, j / 100f));
int yy = (int)(Mathf.Lerp(tmpFront.y * tmpTex.height, tmpBack.y * tmpTex.height, j / 100f));
tmpTex.SetPixel(xx, yy, Color.yellow);
}
}
tmpTex.Apply();
GetComponent<Renderer>().material.mainTexture = tmpTex;
}
static Material lineMaterial;
static void CreateLineMaterial()
{
if (!lineMaterial)
{
// Unity has a built-in shader that is useful for drawing
// simple colored things.
Shader shader = Shader.Find("Hidden/Internal-Colored");
lineMaterial = new Material(shader);
lineMaterial.hideFlags = HideFlags.HideAndDontSave;
// Turn on alpha blending
lineMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
lineMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
// Turn backface culling off
lineMaterial.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off);
// Turn off depth writes
lineMaterial.SetInt("_ZWrite", 0);
}
}
// Will be called after all regular rendering is done
public void OnRenderObject()
{
CreateLineMaterial();
// Apply the line material
lineMaterial.SetPass(0);
GL.PushMatrix();
// Set transformation matrix for drawing to
// match our transform
GL.MultMatrix(transform.localToWorldMatrix);
// Draw lines
GL.Begin(GL.LINES);
// 将透视投影变成正交投影
GL.LoadOrtho();
GL.Color(Color.yellow);
for (int i = 1; i < allPoints.Count; i++)
{
Vector2 tmpFront = allPoints[i-1];
Vector2 tmpBack = allPoints[i];
GL.Vertex3(tmpFront.x, tmpFront.y, 0);
GL.Vertex3(tmpBack.x, tmpBack.y, 0);
}
GL.End();
GL.PopMatrix();
}
List<Vector2> allPoints = new List<Vector2>();
private void Update()
{
if (Input.GetMouseButton(0))
{
Vector2 tmpPos = Camera.main.ScreenToViewportPoint(Input.mousePosition);
allPoints.Add(tmpPos);
}
if (Input.GetMouseButtonUp(0))
{
GenerateText();
//清空屏幕上的点
allPoints.Clear();
}
}
}