您的位置:首页 > 移动开发 > Unity3D

如何在Unity中画抛物线

2016-06-03 11:13 483 查看
最近在开发HTC VIVE VR新品的时候想模仿The Lab中的移动模式,模仿这个功能首先就是要实现抛物线的效果,在网上找了一下发现有很多大家的解决方案,还有一堆关于抛物线的算法,发现不太好用,所以花了点时间自己实现了一个,共享出来欢迎大家来喷。



using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[ExecuteInEditMode]
public class Parabola : MonoBehaviour {
//重力
[Range(0,1)]
public float gravity = 0.13f;
//最大长度
public float maxLength = 50;
//两点之间的距离
const float length = 0.2f;
//点集合
List<Vector3> m_List = new List<Vector3>();
Material m_LineMat;

public void OnRenderObject() {
CreateLineMaterial();
m_LineMat.SetPass(0);

Vector3 position = transform.position;
Vector3 forward = transform.rotation * Vector3.forward * length;
Vector3 newPos = position;
Vector3 lastPos = newPos;
m_List.Add(newPos);
int i = 0, iMax = 0;
float dis = 0;
while (dis < maxLength) {
i++;
newPos = lastPos + forward + Vector3.up * i * -gravity * 0.1f;
dis += Vector3.Distance(lastPos, newPos);
m_List.Add(newPos);
lastPos = newPos;
}

GL.Begin(GL.LINES);
i = 0;
iMax = m_List.Count;
for (i = 0; i < iMax; i++) {
GL.Vertex(m_List[i]);
}
GL.End();

m_List.Clear();
}

void CreateLineMaterial() {
if (!m_LineMat) {
var shader = Shader.Find("Hidden/Internal-Colored");
m_LineMat = new Material(shader);
m_LineMat.hideFlags = HideFlags.HideAndDontSave;
m_LineMat.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
m_LineMat.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
m_LineMat.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off);
m_LineMat.SetInt("_ZWrite", 0);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unity 算法 htc