unity---GL实现案例
GL
C#实现
不管是画任何东西都需要Begin()和End()函数;
画线
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GL_Line : MonoBehaviour
{
// Start is called before the first frame update
// public Material material;
void OnPostRender()
{
// if(!material){
// Debug.LogError("请给材质赋值??");
// return;
// }
// material.SetPass(0);
GL.LoadOrtho();
GL.Begin(GL.LINES);
GL.Color(new Color(255,0,0));//线段颜色
GL.Vertex(new Vector3(0,0,0));
GL.Vertex(new Vector3(100f/Screen.width,100f/Screen.height,0));
GL.End();
}
}
画曲线
根据鼠标位置实时画线
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GL_Curve : MonoBehaviour
{
// Start is called before the first frame update
List lineInfo;
void Start(){
lineInfo=new List();
}
void Update() {
// if(Input.GetMouseButton(0)) // 添加这句话可以控制开始 结束
lineInfo.Add(new Vector3(Input.mousePosition.x/Screen.width,Input.mousePosition.y/Screen.height,0));
}
void OnPostRender()
{
GL.LoadOrtho();
GL.Begin(GL.LINES);
GL.Color(new Color(255,0,0));
for(int i = 0;i
画正方体
需要准备四个点,位置都是浮点数
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GL_Quads : MonoBehaviour
{
// Start is called before the first frame update
private void OnPostRender() {
GL.LoadOrtho();
GL.Begin(GL.QUADS);
GL.Color(new Color(255,0,0));
GL.Vertex(new Vector3(0,0,0));
GL.Vertex(new Vector3(300f/Screen.width,0,0));
GL.Vertex(new Vector3(300f/Screen.width,300f/Screen.height,0));
GL.Vertex(new Vector3(0,300f/Screen.height,0));
GL.End();
}
}
LineRenderer画线
推荐这篇博客
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GL_Line1 : MonoBehaviour
{
// Start is called before the first frame update
public LineRenderer lineRenderer;
// Update is called once per frame
void Start()
{
lineRenderer.positionCount=4;
lineRenderer.startWidth=0.1f;
lineRenderer.endWidth=0.1f;
}
Vector3 v0=new Vector3(1f,0,0);
Vector3 v1=new Vector3(2f,0,0);
Vector3 v2=new Vector3(3f,0,0);
Vector3 v3=new Vector3(4f,0,0);
private void Update() {
lineRenderer.SetPosition(0,v0);
lineRenderer.SetPosition(1,v1);
lineRenderer.SetPosition(2,v2);
lineRenderer.SetPosition(3,v3);
}
}