我试图从脚本生成一个统一的网格。通过在特定方向上进行光线投射来生成网格。然后从命中点或光线终止的位置获取顶点。网格生成很好并且运行良好,但是网格在附加脚本的对象位置上方生成大约5到10个单位单位。我将在下面附上我的脚本。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Torch : MonoBehaviour {
public GameObject lightmeshholder;
private int RaysToShoot = 128;
private float distance = 50;
private Vector3[] vertices;
private Vector2[] vertices2d;
private int[] triangles;
private Mesh mesh;
private Texture2D texture;
private int screenwidth;
private int screenheight;
private int grab = 0;
private RaycastHit hit;
// Use this for initialization
void Start () {
screenwidth = Screen.width;
screenheight = Screen.height;
texture = new Texture2D (screenwidth, screenheight, TextureFormat.RGB24, false);
vertices = new Vector3[RaysToShoot];
vertices2d = new Vector2[RaysToShoot];
triangles = new int[(RaysToShoot) +1 ];
mesh= lightmeshholder.GetComponent<MeshFilter>().mesh;
}
// Update is called once per frame
void Update () {
float angle =0;
for(int i=0;i<RaysToShoot;i++){
float x = Mathf.Sin(0);
x=-5;
if(Input.GetKey(KeyCode.P)){
x = 5;
}
float y = Mathf.Cos(angle);
if (angle <= 90){
angle += 2*Mathf.PI/RaysToShoot;
}
Vector3 dir = new Vector3(x,y,0);
if (Physics.Raycast (this.transform.position, dir,out hit, distance))
{
Debug.DrawLine (this.transform.position, hit.point,new Color(1,1,0,1));
Vector3 tmp = lightmeshholder.transform.InverseTransformPoint(hit.point);
vertices2d[i] = new Vector2(tmp.x,tmp.y);
}else{
Vector3 tmp = lightmeshholder.transform.InverseTransformPoint(this.transform.position + dir*distance);
vertices2d[i] = new Vector2(tmp.x,tmp.y);
Debug.DrawLine(this.transform.position,dir * distance,Color.red,0);
}
}
// build mesh
Vector2[] uvs = new Vector2[vertices2d.Length +1];
Vector3[] newvertices = new Vector3[vertices2d.Length+1];
for (int n = 0; n<newvertices.Length-1 ;n++)
{
if(n==0){
newvertices[0]=this.transform.position;
newvertices[1] = vertices2d[0];
uvs[0] = new Vector2(this.transform.position.x,this.transform.position.y);
uvs[1] = vertices2d[0];
}else{
newvertices[n+1] = vertices2d[n];
uvs[n+1] = vertices2d[n];
}
if(n==0){
triangles[0] = 0;
triangles[1] = 1;
triangles[2] = 2;
}else if(n<newvertices.Length/3){
triangles[n*3] = 0;
triangles[1+n*3] = n+1;
triangles[2+n*3] = n+2;
}
}
Mesh mesh = new Mesh();
GetComponent<MeshFilter>().mesh = mesh;
mesh.Clear();
mesh.vertices = newvertices;
mesh.uv = uvs;
mesh.triangles = triangles;
mesh.RecalculateNormals();
}
}
答案 0 :(得分:3)
您从光线投射获得的生命值是全局的。你可以:
1)确保网格位于位于0,0,0的游戏对象中。每当我创建一个基于光线生命值的动态网格时,我通常会在0,0,0处创建一个新的无父级游戏对象并将网格添加到它。 (而不是从外部获取容器GameObject)
2)在构建网格之前,在光线投射的生命点上调用lightmeshholder.transform.InverseTransformPoint
答案 1 :(得分:0)
当您将顶点指定回网格时,它们将以相对于对象根的本地坐标计算。所以,如果你想把它带回“它应该在哪里”,用.TransformPoint()调用来处理它们以获得适当的偏移量。这应该可以解决您的问题,因为他们位于不同的位置。我有同样的问题。