void OnPointsChanged(Vector3[,] points) { int rowCount = points.GetLength(0); int colCount = points.GetLength(1); #region Calculate line segments for show in SceneView List<Vector3> lineSegments = new List<Vector3>(); for (int i = 0; i < rowCount; i++) { for (int j = 0; j < colCount; j++) { if (i != rowCount - 1) { lineSegments.Add(points[i, j]); lineSegments.Add(points[i + 1, j]); } if (j != colCount - 1) { lineSegments.Add(points[i, j]); lineSegments.Add(points[i, j + 1]); } } } view.SetGrid(lineSegments.ToArray(), Color.white); #endregion #region Calculate cells for Board ThreeTTD.Board.Board board = GameObject.FindObjectOfType<ThreeTTD.Board.Board>(); board.UpdateCellData(points); EditorUtility.SetDirty(board); #endregion }
/// <summary> /// Initializes a new instance of the <see cref="FreezingArcher.Content.Wind"/> class. /// </summary> /// <param name="globalWind">Global wind force.</param> /// <param name="fieldResolution">Wind field resolution.</param> /// <param name="defaultFieldForce">Default field force.</param> public Wind(Vector3 globalWind, Vector3i fieldResolution, Vector3 defaultFieldForce = default(Vector3)) { Global = globalWind; FieldResolution = fieldResolution; WindField = new Vector3[FieldResolution.X, FieldResolution.Y, FieldResolution.Z]; for (int x = 0; x < WindField.GetLength(0); x++) for (int y = 0; y < WindField.GetLength(1); y++) for (int z = 0; z < WindField.GetLength(2); z++) WindField[x, y, z] = defaultFieldForce; }
public static Vector3[,] GridAsWorldCoords() { Vector3[,] grid = new Vector3[Constants.NUMBER_OF_PLAYERS, Constants.VERTICAL_POSITIONS]; for (int x = 0; x < grid.GetLength(0); x++) { for (int y = 0; y < grid.GetLength(1); y++) { grid[x, y] = GridToWorldCoord(0, y, x); } } return(grid); }
private Vector3[,] Initialize() { Vector3[,] result = new Vector3[_screenProvider.GetHeight(), _screenProvider.GetWidth()]; for (int i = 0; i < result.GetLength(0); i++) { for (int j = 0; j < result.GetLength(1); j++) { result[i, j] = _colorProvider.GetBackgroundColor(); } } return(result); }
public void UpdateCellData(Vector3[,] points) { rowCount = points.GetLength(0) - 1; colCount = points.GetLength(1) - 1; cells = new Cell[rowCount * colCount]; for (int i = 0; i < rowCount; i++) { for (int j = 0; j < colCount; j++) { Cell cell = new Cell(new Vector3[4] { points[i, j], points[i, j + 1], points[i + 1, j + 1], points[i + 1, j] }); cells[i * colCount + j] = cell; } } }
private int ClipFillTexture(ref Texture2D RefTexture, int Index, int BaseFrame) { AnimationClip Clip = _Clips [Index]; int TotalFrames = GetClipLength(Clip); Vector3[] BaseMeshVerts = _BaseMesh.vertices; // get base verts Vector3[,] Difference = new Vector3[BaseMeshVerts.Length, TotalFrames]; // create difference array // calculate difference vectors and macimal magnitude float MaxMagniture = 0f; // to find max magnitude for (int y = 0; y < TotalFrames; y++) // for each frame { Vector3[] FrameVerts = GetMesh(Clip, y).vertices; // get mesh at frame for (int x = 0; x < FrameVerts.Length; x++) // for each vertex in frame { Vector3 Vert = FrameVerts[x] - BaseMeshVerts[x]; // gradient of frame now and base mesh Difference [x, y] = Vert; float Magnitude = Vert.magnitude; if (Magnitude > MaxMagniture) { MaxMagniture = Magnitude; } } } // write in the texture for (int x = 0; x < Difference.GetLength(0); x++) { for (int y = 0; y < Difference.GetLength(1); y++) { Vector3 Direction = Difference [x, y]; float Magnitude = Direction.magnitude; Direction = Direction.normalized; RefTexture.SetPixel(x, (BaseFrame + y), new Color( RemappedPos(Direction.x), RemappedPos(Direction.y), RemappedPos(Direction.z), Magnitude / MaxMagniture )); } } _AniClips [Index] = new AniClip(_Clips[Index].name, BaseFrame, TotalFrames, MaxMagniture, _Clips[Index].frameRate); // set AniClip return(BaseFrame + TotalFrames); }
private Vector3[ , ] sample_lidar_normals() { Vector3[ , ] normals = new Vector3[lidar.hit_points.GetLength(0) / 3, lidar.hit_points.GetLength(1)]; for (int i = 0; i < normals.GetLength(0); i++) { for (int j = 0; j < normals.GetLength(1); j++) { Vector3 norm = lidar.hit_normals[i * 3, j]; normals[i, j] = norm; } } return(normals); }
public Vector3[,] GetRays() { Stopwatch watch = new Stopwatch(); watch.Start(); Vector3[,] pixels = new Vector3[ScreenWidth, ScreenHeight]; // calculate the bottom left pixel // we rotate left and down for that double radPerPixelWidth = Vector3.DegToRad(FOV) / ScreenWidth; double radPerPixelHeight = Vector3.DegToRad(FOV) / ScreenWidth; AngleVector viewAngle = ViewDirection.Angle; for (int x = 0; x < pixels.GetLength(0); x++) { for (int y = 0; y < pixels.GetLength(1); y++) { //pixels[x, y] = // new Vector3( // (-ScreenWidth / 2) + x, // (-ScreenHeight / 2) + y, // 0); pixels[x, y] = new Vector3(0, 0, 1) .RotateX((radPerPixelHeight * y) - (radPerPixelHeight * ScreenHeight / 2)) .RotateY((radPerPixelWidth * x) - (radPerPixelWidth * ScreenWidth / 2)); } } for (int x = 0; x < pixels.GetLength(0); x++) { for (int y = 0; y < pixels.GetLength(1); y++) { Vector3 changed = (pixels[x, y].RotateX(viewAngle.Theta - Vector3.DegToRad(90)) .RotateY(-(viewAngle.Phi - (ViewDirection.X == 0 && ViewDirection.Z == 0 ? 0 : Vector3.DegToRad(90)))) );// + (ViewDirection.AsNormalized() * AngleLenght); pixels[x, y] = changed; } } watch.Stop(); Debug.WriteLine("GetRays:" + watch.ElapsedMilliseconds); return(pixels); }
static void Main(string[] args) { var vector3 = new Vector3(1, 1, 1); var vector33 = new Vector3(2, 2, 2); Console.WriteLine(vector3.GetLength()); }
public static Vector3[,] DividePolygon(Vector3[] mainPolygon, int x_divisions, int y_divisions) { Vector3[,] vertices = new Vector3[x_divisions + 2, y_divisions + 2]; Vector3[] side_x_top = DivideSide(mainPolygon[1], mainPolygon[2], x_divisions); Vector3[] side_x_bot = DivideSide(mainPolygon[0], mainPolygon[3], x_divisions); Vector3[] side_y_left = DivideSide(mainPolygon[0], mainPolygon[1], y_divisions); Vector3[] side_y_right = DivideSide(mainPolygon[3], mainPolygon[2], y_divisions); for (int i = 0; i < side_y_left.Length; i++) { vertices[0, i] = side_y_left[i]; } for (int i = 0; i < side_y_right.Length; i++) { vertices[vertices.GetLength(0) - 1, i] = side_y_right[i]; } for (int x = 1; x <= x_divisions; x++) { Vector3 from = side_x_bot[x]; Vector3 to = side_x_top[x]; Vector3[] vertical_y = DivideSide(from, to, y_divisions); for (int y = 0; y < vertical_y.Length; y++) { vertices[x, y] = vertical_y[y]; } } return(vertices); }
private Vector3[,] GetPoints() { var diffa = (float)Math.PI * 2 / PointCountH; var diffb = (float)Math.PI * 2 / PointCountV; var ret = new Vector3[PointCountH, PointCountV]; for (int i = 0; i < ret.GetLength(0); i++) { for (int j = 0; j < ret.GetLength(1); j++) { ret[i, j] = GetPoint(i * diffa, j * diffb, TubeRadius, TorusRadius); } } return(ret); }
/// <summary> /// From min and max coords of the BB, project them according to the active view, for determining zooming scale /// </summary> /// <param name="min"> The min coord of BB </param> /// <param name="max"> The max coord of BB </param> /// <param name="activeView"> Active view to zoom </param> /// <returns> Returns an array of two vectos in screen space </returns> private Vector2[] findMaxPoints(Vector3 min, Vector3 max, Canguro.View.GraphicView activeView) { Vector3[] boundingVolume = new Vector3[8]; Vector2[] screen = new Vector2[2]; screen[0] = new Vector2(float.MaxValue, float.MaxValue); screen[1] = new Vector2(float.MinValue, float.MinValue); boundingVolume[0] = min; boundingVolume[1] = new Vector3(min.X, min.Y, max.Z); boundingVolume[2] = new Vector3(max.X, min.Y, max.Z); boundingVolume[3] = new Vector3(max.X, min.Y, min.Z); boundingVolume[4] = new Vector3(max.X, max.Y, min.Z); boundingVolume[5] = max; boundingVolume[6] = new Vector3(min.X, max.Y, max.Z); boundingVolume[7] = new Vector3(min.X, max.Y, min.Z); for (int i = 0; i < boundingVolume.GetLength(0); ++i) { activeView.Project(ref boundingVolume[i]); screen[0].X = (screen[0].X > boundingVolume[i].X) ? boundingVolume[i].X : screen[0].X; screen[0].Y = (screen[0].Y > boundingVolume[i].Y) ? boundingVolume[i].Y : screen[0].Y; screen[1].X = (screen[1].X < boundingVolume[i].X) ? boundingVolume[i].X : screen[1].X; screen[1].Y = (screen[1].Y < boundingVolume[i].Y) ? boundingVolume[i].Y : screen[1].Y; } return(screen); }
public static double Angle(Vector3 pDirection, Plane pPlane) { return(System.Math.Asin( System.Math.Abs(Vector3.DotProduct(pDirection, pPlane.Normal)) / (pDirection.GetLength() * pPlane.Normal.GetLength()) )); }
private static Vector3 SetLength(Vector3 v, float d) { // TODO // omg... :'( var l = v.GetLength(); if (l < ToleranceLength && l > -ToleranceLength) { return(v); } else if (l == ReferenceLength) { return(v); // watn glück...^^ } else if (l < ReferenceLength) { var ld = ReferenceLength - l; return(v.MakeLonger(ld)); } else if (l > ReferenceLength) { var ld = l - ReferenceLength; return(v.MakeLonger(-ld)); } else { // 42... return(v); } }
public Vector3[,] getPositionGridSquare(int numberOfRows, Vector3 destination) { Vector3[,] map = new Vector3[(2 * numberOfRows) - 1, (2 * numberOfRows) - 1]; int center = numberOfRows; Vector3 soldierPosition = new Vector3(destination.x - (numberOfRows * 2), 0, destination.z - (numberOfRows) * 2);//position of first soldier float xPosFirst = soldierPosition.x; float yPosFirst = soldierPosition.z; for (int i = 0; i < map.GetLength(0); i++) { for (int j = 0; j < map.GetLength(1); j++) { map[i, j] = new Vector3(xPosFirst + (i * 2), 0, yPosFirst + (j * 2)); } } return(map); }
public void setOutlines(Vector3[,] newOutlines, Color newcolor) { if(newOutlines.GetLength(0)>0) { outlines.Add(newOutlines); //Debug.Log ("no "+newOutlines.GetLength(0).ToString()); colors.Add(newcolor); } }
private void BuildNormalmap() { NormalMap = new Vector3[Heightmap.GetLength(0), Heightmap.GetLength(1)]; for (int x = 0; x < NormalMap.GetLength(0); x++) { for (int z = 0; z < NormalMap.GetLength(1); z++) { var v1 = HeightVectorAt(x, z); var v2 = HeightVectorAt(x - 1, z); var v3 = HeightVectorAt(x, z + 1); var v4 = HeightVectorAt(x + 1, z + 1); var v5 = HeightVectorAt(x + 1, z); var v6 = HeightVectorAt(x, z - 1); var v7 = HeightVectorAt(x - 1, z - 1); var normal = CalculateNormal(v1, v2, v3, v4, v5, v6, v7, v2, v3, v5, v6, v1, v1, v1, v1, v1); NormalMap[x, z] = normal; } } }
/// <summary> /// 移動経路の追加 /// </summary> /// <param name="pos">追加する経路の位置</param> public void AddPath(Vector3 pos) { Vector3[] newPath = new Vector3[movePath.GetLength(0) + 1]; for (int i = 0; i < movePath.GetLength(0); i++) { newPath[i] = movePath[i]; } newPath[newPath.GetLength(0) - 1] = pos; movePath = newPath; }
public override Vector3[,,] BuildVertexMatrix(float height, float width, float depth) { //prevent negative values width = Mathf.Abs(width); // the amount of multiples of radius height = Mathf.Abs(height); // the amount of sectors depth = Mathf.Abs(depth); // the amount of layers (times 2) Vector3[,,] vertexMatrix = new Vector3[Mathf.RoundToInt(width), Mathf.Min(Mathf.RoundToInt(height), sectors), 2 * Mathf.RoundToInt(depth) + 1]; // fill the matrix for (int k = 0; k < vertexMatrix.GetLength(2); k++) { for (int i = 1; i <= vertexMatrix.GetLength(0); i++) { for (int j = 0; j < vertexMatrix.GetLength(1); j++) { vertexMatrix[i - 1, j, k] = GridToWorld(new Vector3(i, j, k - Mathf.RoundToInt(width))); } } } return(vertexMatrix); }
Vector3[][] MakeLines(float[,] geom, int[][] geomIndexLines = null) { Vector3[][] vLines = new Vector3[(geomIndexLines != null) ? geomIndexLines.GetLength(0) : 1][]; // No line indices then default to 1 line for (int i = 0; i < vLines.GetLength(0); i++) { vLines[i] = new Vector3[(geomIndexLines != null) ? geomIndexLines[i].Length : geom.GetLength(0)]; // No line indices then default to all geometry for (int v = 0; v < vLines[i].Length; v++) { vLines[i][v] = (geomIndexLines != null) ? new Vector3(geom[geomIndexLines[i][v], 0], geom[geomIndexLines[i][v], 1], geom[geomIndexLines[i][v], 2]) : new Vector3(geom[v, 0], geom[v, 1], geom[v, 2]); } } return(vLines); }
public void ReducePathLenghtByDist(float dist) { if (GetPathType() == PathType.Blank) { Log.outError(LogFilter.Maps, "PathGenerator.ReducePathLenghtByDist called before path was built"); return; } if (_pathPoints.Length < 2) // path building failure { return; } int i = _pathPoints.Length; Vector3 nextVec = _pathPoints[--i]; while (i > 0) { Vector3 currVec = _pathPoints[--i]; Vector3 diffVec = (nextVec - currVec); float len = diffVec.GetLength(); if (len > dist) { float step = dist / len; // same as nextVec _pathPoints[i + 1] -= diffVec * step; _sourceUnit.UpdateAllowedPositionZ(_pathPoints[i + 1].X, _pathPoints[i + 1].Y, ref _pathPoints[i + 1].Z); Array.Resize(ref _pathPoints, i + 2); break; } else if (i == 0) // at second point { _pathPoints[1] = _pathPoints[0]; Array.Resize(ref _pathPoints, 2); break; } dist -= len; nextVec = currVec; // we're going backwards } }
private Vector3[,] GenerateCircleVertices(int radialSegments, float outerRadius, int tubeSegments, float tubeLength) { Vector3 currentVertex = new Vector3(); Vector3[,] vertices = new Vector3[radialSegments + 1, 1 + tubeSegments]; float PI2 = 2 * Mathf.PI; float fracturedLength = tubeLength / (float)tubeSegments; for (int i = 0; i <= radialSegments; i++) { float r1 = (float)(i % radialSegments) / radialSegments * PI2; float cos = Mathf.Cos(r1); float sin = Mathf.Sin(r1); currentVertex = new Vector3(cos * outerRadius, 0, sin * outerRadius); for (int j = 0; j < vertices.GetLength(1); j++) { currentVertex.y = j * fracturedLength; vertices[i, j] = currentVertex; } } return(vertices); }
public void MovementTest() { PlayerMovement pm = new PlayerMovement(); //Compares moveVar loactions to x,y coordinates //testata is the known locations //testPos is the moveVar Vector3[] testData = new Vector3[8]; float[] testPos = new float[8]; testData[0] = new Vector3(0, 3, 0); testData[1] = new Vector3(2.1f, 2.1f, 0); testData[2] = new Vector3(3, 0, 0); testData[3] = new Vector3(2.1f, -2.1f, 0); testData[4] = new Vector3(0, -3, 0); testData[5] = new Vector3(-2.1f, -2.1f, 0); testData[6] = new Vector3(-3, 0, 0); testData[7] = new Vector3(-2.1f, 2.1f, 0); testPos[0] = 0; testPos[1] = 0.785f; testPos[2] = 1.57f; testPos[3] = 2.37f; testPos[4] = 3.14f; testPos[5] = 3.92f; testPos[6] = 4.71f; testPos[7] = 5.49f; for (int i = 0; i < testData.GetLength(0); ++i) { Vector3 testAnswer = pm.GetNextLocation(testPos[i]); Assert.AreEqual(testAnswer.x, testData[i].x, 0.06); Assert.AreEqual(testAnswer.y, testData[i].y, 0.06); } }
void UpdateMassSpringsMesh() { Vector3[,] offsets = new Vector3[Masses.Count, dic_Force.Count]; Dictionary <int, Vector3> .Enumerator it = dic_Force.GetEnumerator(); int forceIdx = 0; while (it.MoveNext()) { int vertexIdx = it.Current.Key; Vector3 force = it.Current.Value; offsets[vertexIdx, forceIdx++] = force; } // 多组质点弹簧遍历 it = dic_Force.GetEnumerator(); Queue <int> masses = new Queue <int> (); HashSet <int> mark = new HashSet <int> (); forceIdx = 0; while (it.MoveNext()) { int vidx_force = it.Current.Key; Vector3 force = it.Current.Value; offsets[vidx_force, forceIdx] = force; masses.Clear(); mark.Clear(); masses.Enqueue(vidx_force); mark.Add(vidx_force); // 一组质点弹簧遍历 while (masses.Count > 0) { int vidx = masses.Dequeue(); Vector3 delta = offsets[vidx, forceIdx]; // 遍历此节点所有链接点 Dictionary <int, float> edge = MassSprings [vidx]; Dictionary <int, float> .Enumerator iter = edge.GetEnumerator(); while (iter.MoveNext()) { int idx = iter.Current.Key; float value = iter.Current.Value; int key = vidx > idx ? vidx | (idx << 16) : (vidx << 16) | idx; if (mark.Contains(key)) { continue; } Vector3 v = delta / (1 + value / kViscosity); if (v.magnitude <= kThresholdZero) { continue; } if (!dic_Force.ContainsKey(idx) && offsets[idx, forceIdx].sqrMagnitude < v.sqrMagnitude) { offsets[idx, forceIdx] = v; masses.Enqueue(idx); } } iter = edge.GetEnumerator(); while (iter.MoveNext()) { int idx = iter.Current.Key; int key = vidx > idx ? vidx | (idx << 16) : (vidx << 16) | idx; mark.Add(key); } } forceIdx++; } // 计算各顶点偏移量 for (int i = 0; i < offsets.GetLength(0); i++) { Vector3 result = Vector3.zero; // 计算改顶点最终形变量(x,y,z) for (int j = 0; j < 3; j++) { float positive = 0f; float negative = 0f; for (int k = 0; k < dic_Force.Count; k++) { Vector3 offset = offsets [i, k]; float v = offset [j]; if (v > 0 && v > positive) { positive = v; } else if (v < 0 && v < negative) { negative = v; } } result [j] = positive + negative; } // 最终结果保存在第一个位置 offsets [i, 0] = result; } // 计算出最新的质点位置 for (int i = 0; i < Masses.Count; i++) { MassPoint mass = Masses [i]; mass.pos += offsets [i, 0]; for (int j = 0; j < mass.vertices.Count; j++) { int vid = mass.vertices [j]; originalVertices [vid] = originalVertices [vid] + offsets [i, 0]; } } }
// TODO: just a testing function with rectangles private void DrawCurveBrushSamplePointsAsGrid(Vector3 position, Vector3 normal, Color innerColor, Color outerColor, AnimationCurve curveX, AnimationCurve curveZ) { // number of sample points in 1 direction, i. e. there will be n * n sample points int samplePointsPerRow = gizmo.brushSettings.curveSamplePoints; // the sample point distance on a [0,1] range, i. e. for 10 the distance will be 0.1 float samplePointDistanceNormalized = 1f / samplePointsPerRow; Vector3[,] v = new Vector3[samplePointsPerRow, samplePointsPerRow]; Color[,] c = new Color[samplePointsPerRow, samplePointsPerRow]; int i; int j; for (i = 0; i < samplePointsPerRow; i++) { for (j = 0; j < samplePointsPerRow; j++) { float x = i * samplePointDistanceNormalized; float z = j * samplePointDistanceNormalized; float curvePointX = curveX.Evaluate(x); float curvePointZ = curveZ.Evaluate(z); // ensure value is [0,1] curvePointX = Mathf.Clamp01(curvePointX); curvePointZ = Mathf.Clamp01(curvePointZ); float discSize = gizmo.brushSettings.brushSize * x; // is same as y Handles.color = new Color(innerColor.r, innerColor.g, innerColor.b, curvePointX * curvePointZ); float radius = gizmo.brushSettings.brushSize * samplePointDistanceNormalized * 0.5f; // TODO: align depending on brush size float xPosition = position.x - gizmo.brushSettings.brushSize * (x - 0.5f) - radius; float zPosition = position.z - gizmo.brushSettings.brushSize * (z - 0.5f) - radius; // high enough offset for y, in case the terrain below the brush aligned in it's normal direction isn't flat // otherwise parts might be above terrain while others might be below it; another way would be to do an additional up raycast float yRaystOffset = 3000f; float yPosition = position.y + yRaystOffset; // individual disc position, but with y offset Vector3 discPosition = new Vector3(xPosition, yPosition, zPosition); // rotate around y world axis float angle = gizmo.brushSettings.brushRotation; discPosition -= position; // move to origin discPosition = Quaternion.Euler(0, angle, 0) * discPosition; // rotate around world axis discPosition += position; // move back to position // y via raycast down // TODO: raycast hit against layer // see https://docs.unity3d.com/ScriptReference/Physics.Raycast.html RaycastHit hit; if (Physics.Raycast(discPosition, Vector3.down, out hit, Mathf.Infinity)) { // set y position depending on the terrain discPosition.y = hit.point.y; // set the normal depending on the terrain normal = hit.normal; } // y via height sampling // discPosition.y = Terrain.activeTerrain.SampleHeight(discPosition); v[i, j] = discPosition; c[i, j] = Handles.color; // slope float slopeAngle = Vector3.Angle(normal.normalized, new Vector3(0, 1, 0)); //Handles.Label(discPosition, new GUIContent("angle: " + slopeAngle)); // if brush area isn't inside the slope range, make the color almost transparent if (slopeAngle < gizmo.brushSettings.slopeMin || slopeAngle > gizmo.brushSettings.slopeMax) { c[i, j].a = 0.05f; } } } for (i = 0; i < v.GetLength(0) - 1; i++) { for (j = 0; j < v.GetLength(1) - 1; j++) { Vector3[] verts = new Vector3[] { v[i, j], v[i, j + 1], v[i + 1, j + 1], v[i + 1, j], }; Handles.DrawSolidRectangleWithOutline(verts, c[i, j], new Color(0, 0, 0, c[i, j].a)); } } }
public GameObject GenerateGroundArea(GroundSet[] cubePrefs, int pieces, int w, int l, float maxDist) { // v 2 // pick num of different pieces, then generate floor from that number of points if (cubePrefs.Length < 2) { return(new GameObject("No ground generated.")); } Vector2 center = new Vector2(w / 2, l / 2); int differentPieces = pieces;//Random.Range(1, cubePrefs.Length); // generate vectors Vector3 offset = Vector3.zero; Vector3[,] generatedPositions = new Vector3[w, l]; for (int i = 0; i < w; i++) { for (int j = 0; j < l; j++) { generatedPositions[i, j] = (new Vector3(i, j) + offset); } } // choose n random vectors Vector3[] rndPositions = new Vector3[differentPieces]; for (int i = 0; i < differentPieces; i++) { rndPositions[i] = generatedPositions[Random.Range(0, generatedPositions.GetLength(0)), Random.Range(0, generatedPositions.GetLength(1))]; } // flood cubes from those positions, choose id for cube int[,] finalMap = new int[w, l]; Queue <Vector3> floodQue = new Queue <Vector3>(); // assign starting values for (int i = 0; i < differentPieces; i++) { floodQue.Enqueue(rndPositions[i]); finalMap[(int)rndPositions[i].x, (int)rndPositions[i].y] = (i % cubePrefs.Length + 1); } // flood those values // Note: 0 means unassigned int lastI = 0; bool diamantGen = false; while (floodQue.Count > 0) { Vector3 p = floodQue.Dequeue(); int x = (int)p.x; int y = (int)p.y; if (diamantGen) { int i = Random.Range(0, cubePrefs.Length); if (i == lastI) { i = (lastI + 1) % cubePrefs.Length; } lastI = i; bool oneOnly = true; if ((oneOnly && i == 0) || !oneOnly) { if (x + 1 < w && finalMap[x + 1, y] == 0 && Random.Range(0, 1) < 0.7f) { finalMap[x + 1, y] = finalMap[x, y]; floodQue.Enqueue(generatedPositions[x + 1, y]); } } if ((oneOnly && i == 1) || !oneOnly) { if (x - 1 >= 0 && finalMap[x - 1, y] == 0 && Random.Range(0, 1) < 0.7f) { finalMap[x - 1, y] = finalMap[x, y]; floodQue.Enqueue(generatedPositions[x - 1, y]); } } if ((oneOnly && i == 2) || !oneOnly) { if (y + 1 < l && finalMap[x, y + 1] == 0 && Random.Range(0, 1) < 0.7f) { finalMap[x, y + 1] = finalMap[x, y]; floodQue.Enqueue(generatedPositions[x, y + 1]); } } if ((oneOnly && i == 3) || !oneOnly) { if (y - 1 >= 0 && finalMap[x, y - 1] == 0 && Random.Range(0, 1) < 0.7f) { finalMap[x, y - 1] = finalMap[x, y]; floodQue.Enqueue(generatedPositions[x, y - 1]); } } if (x + 1 < w && y + 1 < l && finalMap[x + 1, y + 1] == 0 && Random.Range(0, 1) < 0.3f) { finalMap[x + 1, y + 1] = finalMap[x, y]; floodQue.Enqueue(generatedPositions[x + 1, y + 1]); } if (x + 1 < w && y - 1 >= 0 && finalMap[x + 1, y - 1] == 0 && Random.Range(0, 1) < 0.3f) { finalMap[x + 1, y - 1] = finalMap[x, y]; floodQue.Enqueue(generatedPositions[x + 1, y - 1]); } if (x - 1 >= 0 && y + 1 < l && finalMap[x - 1, y + 1] == 0 && Random.Range(0, 1) < 0.3f) { finalMap[x - 1, y + 1] = finalMap[x, y]; floodQue.Enqueue(generatedPositions[x - 1, y + 1]); } if (x - 1 >= 0 && y - 1 >= 0 && finalMap[x - 1, y - 1] == 0 && Random.Range(0, 1) < 0.3f) { finalMap[x - 1, y - 1] = finalMap[x, y]; floodQue.Enqueue(generatedPositions[x - 1, y - 1]); } } else { int i = Random.Range(0, cubePrefs.Length); if (i == lastI) { i = (lastI + 1) % cubePrefs.Length; } lastI = i; bool oneOnly = true; if ((oneOnly && i == 0) || !oneOnly) { if (x + 1 < w && finalMap[x + 1, y] == 0 && Random.Range(0, 1) < 0.3f) { finalMap[x + 1, y] = finalMap[x, y]; floodQue.Enqueue(generatedPositions[x + 1, y]); } } if ((oneOnly && i == 1) || !oneOnly) { if (x - 1 >= 0 && finalMap[x - 1, y] == 0 && Random.Range(0, 1) < 0.3f) { finalMap[x - 1, y] = finalMap[x, y]; floodQue.Enqueue(generatedPositions[x - 1, y]); } } if ((oneOnly && i == 2) || !oneOnly) { if (y + 1 < l && finalMap[x, y + 1] == 0 && Random.Range(0, 1) < 0.3f) { finalMap[x, y + 1] = finalMap[x, y]; floodQue.Enqueue(generatedPositions[x, y + 1]); } } if ((oneOnly && i == 3) || !oneOnly) { if (y - 1 >= 0 && finalMap[x, y - 1] == 0 && Random.Range(0, 1) < 0.3f) { finalMap[x, y - 1] = finalMap[x, y]; floodQue.Enqueue(generatedPositions[x, y - 1]); } } if (x + 1 < w && y + 1 < l && finalMap[x + 1, y + 1] == 0 && Random.Range(0, 1) < 0.7f) { finalMap[x + 1, y + 1] = finalMap[x, y]; floodQue.Enqueue(generatedPositions[x + 1, y + 1]); } if (x + 1 < w && y - 1 >= 0 && finalMap[x + 1, y - 1] == 0 && Random.Range(0, 1) < 0.7f) { finalMap[x + 1, y - 1] = finalMap[x, y]; floodQue.Enqueue(generatedPositions[x + 1, y - 1]); } if (x - 1 >= 0 && y + 1 < l && finalMap[x - 1, y + 1] == 0 && Random.Range(0, 1) < 0.7f) { finalMap[x - 1, y + 1] = finalMap[x, y]; floodQue.Enqueue(generatedPositions[x - 1, y + 1]); } if (x - 1 >= 0 && y - 1 >= 0 && finalMap[x - 1, y - 1] == 0 && Random.Range(0, 1) < 0.7f) { finalMap[x - 1, y - 1] = finalMap[x, y]; floodQue.Enqueue(generatedPositions[x - 1, y - 1]); } } } /*float[] randomWeights = new float[cubePrefs.Length]; * float min = 1; * for (int i = (int)Random.Range(0f, 1f) * cubePrefs.Length; i < cubePrefs.Length; i++) { * randomWeights[i] = Random.Range(min, 1); * min = randomWeights[i]; * } * for (int i = 0; i < w; i++) { * for (int j = 0; j < w; j++) { * int randI = Random.Range(0, cubePrefs.Length); * finalMap[i, j] = (int)(finalMap[i, j] + randI+1)/2; * //bool spawn = Random.Range(0, 1) < randomWeights[i]; * //if (spawn) { * //Transform t = Instantiate(cubePrefs[randI], new Vector3(i, j), new Quaternion(), ground.transform); * //} * } * }*/ // create map in a shape of a circle for (int i = 0; i < finalMap.GetLength(0); i++) { for (int j = 0; j < finalMap.GetLength(1); j++) { if (Vector3.Distance(center, generatedPositions[i, j]) > maxDist) { finalMap[i, j] = -1; } } } Queue <Vector3> edgeCoordinates = new Queue <Vector3>(); for (int i = 0; i < w; i++) { for (int j = 0; j < l; j++) { // find edge cases up and down if ((j - 1 > 0 && finalMap[i, j - 1] == -1 && finalMap[i, j - 1] != finalMap[i, j]) || (i - 1 > 0 && finalMap[i - 1, j] == -1 && finalMap[i - 1, j] != finalMap[i, j])) { edgeCoordinates.Enqueue(new Vector3(i, j)); } } } // extend the circle into uneven shapes while (edgeCoordinates.Count > 0) { Vector3 v = edgeCoordinates.Dequeue(); int x = (int)v.x; int y = (int)v.y; //finalMap[(int)v.x+1, (int)v.y] = finalMap[(int) v.x, (int)v.y]; //finalMap[(int)v.x, (int)v.y+1] = finalMap[(int) v.x, (int)v.y]; //finalMap[(int)v.x-1, (int)v.y] = finalMap[(int) v.x, (int)v.y]; //finalMap[(int)v.x, (int)v.y-1] = finalMap[(int) v.x, (int)v.y]; int required = -1; if (x + 1 < w && finalMap[x + 1, y] == required && Random.Range(0, 1) < 0.3f) { finalMap[x + 1, y] = finalMap[x, y]; floodQue.Enqueue(generatedPositions[x + 1, y]); } if (x - 1 >= 0 && finalMap[x - 1, y] == required && Random.Range(0, 1) < 0.3f) { finalMap[x - 1, y] = finalMap[x, y]; floodQue.Enqueue(generatedPositions[x - 1, y]); } if (y + 1 < w && finalMap[x, y + 1] == required && Random.Range(0, 1) < 0.3f) { finalMap[x, y + 1] = finalMap[x, y]; floodQue.Enqueue(generatedPositions[x, y + 1]); } if (y - 1 >= 0 && finalMap[x, y - 1] == required && Random.Range(0, 1) < 0.3f) { finalMap[x, y - 1] = finalMap[x, y]; floodQue.Enqueue(generatedPositions[x, y - 1]); } } GameObject ground = new GameObject("Ground"); for (int i = 0; i < finalMap.GetLength(0); i++) { for (int j = 0; j < finalMap.GetLength(1); j++) { int x = (int)generatedPositions[i, j].x; int y = (int)generatedPositions[i, j].y; if (finalMap[x, y] == -1) { continue; } if (finalMap[x, y] == 0) { finalMap[x, y] = 1; } Quaternion rot = Quaternion.Euler(0, Random.Range(0, 8) * 90, 0); // choose random max or min or nothing height Vector3 pos = new Vector3(i, 0, j); if (Random.Range(0f, 1f) < rndHeightChance) { if (Random.Range(0f, 1f) < 0.5f) { pos = new Vector3(i, lowHeightBlock, j); } else { pos = new Vector3(i, highHeighBlock, j); } } GroundSet set = cubePrefs[finalMap[x, y] - 1]; Transform t = Instantiate(set.Get(), pos, rot, ground.transform); } } return(ground); /* // v 1 * float[] randomWeights = new float[cubePrefs.Length]; * float min = 1; * for (int i = (int)Random.Range(0f, 1f)*cubePrefs.Length; i < cubePrefs.Length; i++) { * randomWeights[i] = Random.Range(min, 1); * min = randomWeights[i]; * } * * GameObject ground= new GameObject("Ground"); * for (int i = 0; i < w; i++) { * for (int j = 0; j < w; j++) { * int randI = Random.Range(0, cubePrefs.Length); * finalQue[i, j] = randI; * //bool spawn = Random.Range(0, 1) < randomWeights[i]; * //if (spawn) { * Transform t = Instantiate(cubePrefs[randI], new Vector3(i, j), new Quaternion(), ground.transform); * //} * } * } * * return ground;*/ }
// Update is called once per frame void Update() { if (this.pointList == null || this.pointList.Count < 2) { this.lineMesh.Clear(); this.lineMesh.vertices = new Vector3[0]; this.lineMesh.triangles = new int[0]; this.lineMesh.normals = new Vector3[0]; this.lineMesh.uv = new Vector2[0]; this.lineMesh.colors = new Color[0]; return; } Vector3[] meshVertices = new Vector3[(this.pointList.Count * 8) + 8]; int[] meshTriangles = new int[((this.pointList.Count - 1) * 24) + 12]; Vector3[] meshNormals = new Vector3[(this.pointList.Count * 8) + 8]; Vector2[] meshUVs = new Vector2[(this.pointList.Count * 8) + 8]; Color[] meshColors = new Color[(this.pointList.Count * 8) + 8]; Vector3 position = this.transform.position; Vector3 up = Vector3.zero; Vector3 forward = this.transform.forward; Vector3 right = Vector3.zero; Vector3 upNormal = this.transform.up; Vector3 rightNormal = this.transform.right; Vector3 forwardNormal = this.transform.forward; Vector3 lastUpNormal = upNormal; Vector3 lastRightNormal = rightNormal; Vector3 lastForwardNormal = forwardNormal; Vector3 lastForward = forward; Vector3 tempVector = Vector3.zero; Vector3 planeNormal = this.transform.forward; float currentLength = 0.0f; float xPosUV = 1.0f; int pointIndex = 0; position = this.pointList[0].position; up = this.pointList[0].normal * this.pointList[0].height; forward = this.pointList[1].position - position; if (forward == Vector3.zero) forward = lastForward; lastForward = forward; forwardNormal = forward.normalized; if (forwardNormal == Vector3.zero) forwardNormal = lastForwardNormal; lastForwardNormal = forwardNormal; right = Vector3.Cross(up, forward).normalized * this.pointList[0].width; tempVector = position + (right * 0.5f) + up; meshVertices[pointIndex] = tempVector; meshNormals[pointIndex] = -forwardNormal; meshColors[pointIndex] = this.pointList[0].color; meshUVs[pointIndex] = new Vector2(xPosUV, 1.0f); pointIndex++; tempVector = position - (right * 0.5f) + up; meshVertices[pointIndex] = tempVector; meshNormals[pointIndex] = -forwardNormal; meshColors[pointIndex] = this.pointList[0].color; meshUVs[pointIndex] = new Vector2(xPosUV, 1.0f); pointIndex++; tempVector = position + (right * 0.5f); meshVertices[pointIndex] = tempVector; meshNormals[pointIndex] = -forwardNormal; meshColors[pointIndex] = this.pointList[0].color; meshUVs[pointIndex] = new Vector2(xPosUV, 0.0f); pointIndex++; tempVector = position - (right * 0.5f); meshVertices[pointIndex] = tempVector; meshNormals[pointIndex] = -forwardNormal; meshColors[pointIndex] = this.pointList[0].color; meshUVs[pointIndex] = new Vector2(xPosUV, 0.0f); for (int i = 0; i < this.pointList.Count; i++) { if (i > 0) currentLength += (this.pointList[i].position - this.pointList[i - 1].position).magnitude; xPosUV = 1.0f - (currentLength / this.baseLength); position = this.pointList[i].position; up = this.pointList[i].normal * this.pointList[i].height; if (i == this.pointList.Count - 1) forward = -(this.pointList[i - 1].position - position); else forward = this.pointList[i + 1].position - position; if (forward == Vector3.zero) forward = lastForward; planeNormal = this.GetDiagonalPlaneNormal(forward, -lastForward); lastForward = forward; upNormal = up.normalized; if (upNormal == Vector3.zero) upNormal = lastUpNormal; lastUpNormal = upNormal; rightNormal = right.normalized; if (rightNormal == Vector3.zero) rightNormal = lastRightNormal; lastRightNormal = rightNormal; right = Vector3.Cross(up, forward).normalized * this.pointList[i].width * 0.5f; right = this.FindVertexPos(planeNormal, right); up = this.FindVertexPos(planeNormal, up); pointIndex = 4 + (i * 8); tempVector = position + right + up; meshVertices[pointIndex] = tempVector; meshNormals[pointIndex] = upNormal; meshColors[pointIndex] = this.pointList[i].color; meshUVs[pointIndex] = new Vector2(xPosUV, 1.0f); pointIndex++; meshVertices[pointIndex] = tempVector; meshNormals[pointIndex] = rightNormal; meshColors[pointIndex] = this.pointList[i].color; meshUVs[pointIndex] = new Vector2(xPosUV, 1.0f); pointIndex++; tempVector = position - right + up; meshVertices[pointIndex] = tempVector; meshNormals[pointIndex] = upNormal; meshColors[pointIndex] = this.pointList[i].color; meshUVs[pointIndex] = new Vector2(xPosUV, 1.0f); pointIndex++; meshVertices[pointIndex] = tempVector; meshNormals[pointIndex] = -rightNormal; meshColors[pointIndex] = this.pointList[i].color; meshUVs[pointIndex] = new Vector2(xPosUV, 1.0f); pointIndex++; tempVector = position + right; meshVertices[pointIndex] = tempVector; meshNormals[pointIndex] = -upNormal; meshColors[pointIndex] = this.pointList[i].color; meshUVs[pointIndex] = new Vector2(xPosUV, 0.0f); pointIndex++; meshVertices[pointIndex] = tempVector; meshNormals[pointIndex] = rightNormal; meshColors[pointIndex] = this.pointList[i].color; meshUVs[pointIndex] = new Vector2(xPosUV, 0.0f); pointIndex++; tempVector = position - right; meshVertices[pointIndex] = tempVector; meshNormals[pointIndex] = -upNormal; meshColors[pointIndex] = this.pointList[i].color; meshUVs[pointIndex] = new Vector2(xPosUV, 0.0f); pointIndex++; meshVertices[pointIndex] = tempVector; meshNormals[pointIndex] = -rightNormal; meshColors[pointIndex] = this.pointList[i].color; meshUVs[pointIndex] = new Vector2(xPosUV, 0.0f); } pointIndex = meshVertices.GetLength(0) - 4; position = this.pointList[this.pointList.Count - 1].position; up = this.pointList[this.pointList.Count - 1].normal * this.pointList[this.pointList.Count - 1].height; forward = -(this.pointList[this.pointList.Count - 2].position - position); if (forward == Vector3.zero) forward = lastForward; lastForward = forward; forwardNormal = forward.normalized; if (forwardNormal == Vector3.zero) forwardNormal = lastForwardNormal; lastForwardNormal = forwardNormal; right = Vector3.Cross(up, forward).normalized * this.pointList[this.pointList.Count - 1].width; tempVector = position + (right * 0.5f) + up; meshVertices[pointIndex] = tempVector; meshNormals[pointIndex] = forwardNormal; meshColors[pointIndex] = this.pointList[this.pointList.Count - 1].color; meshUVs[pointIndex] = new Vector2(1.0f, 1.0f); pointIndex++; tempVector = position - (right * 0.5f) + up; meshVertices[pointIndex] = tempVector; meshNormals[pointIndex] = forwardNormal; meshColors[pointIndex] = this.pointList[this.pointList.Count - 1].color; meshUVs[pointIndex] = new Vector2(1.0f, 1.0f); pointIndex++; tempVector = position + (right * 0.5f); meshVertices[pointIndex] = tempVector; meshNormals[pointIndex] = forwardNormal; meshColors[pointIndex] = this.pointList[this.pointList.Count - 1].color; meshUVs[pointIndex] = new Vector2(1.0f, 0.0f); pointIndex++; tempVector = position - (right * 0.5f); meshVertices[pointIndex] = tempVector; meshNormals[pointIndex] = forwardNormal; meshColors[pointIndex] = this.pointList[this.pointList.Count - 1].color; meshUVs[pointIndex] = new Vector2(1.0f, 0.0f); int nextPointIndex = 0; int triIndex = 0; meshTriangles[triIndex] = 0; triIndex++; meshTriangles[triIndex] = 2; triIndex++; meshTriangles[triIndex] = 1; triIndex++; meshTriangles[triIndex] = 1; triIndex++; meshTriangles[triIndex] = 2; triIndex++; meshTriangles[triIndex] = 3; for (int i = 0; i < this.pointList.Count - 1; i++) { pointIndex = 4 + (i * 8); nextPointIndex = 4 + ((i + 1) * 8); triIndex = 6 + (i * 24); meshTriangles[triIndex] = pointIndex; triIndex++; meshTriangles[triIndex] = pointIndex + 2; triIndex++; meshTriangles[triIndex] = nextPointIndex; triIndex++; meshTriangles[triIndex] = pointIndex + 2; triIndex++; meshTriangles[triIndex] = nextPointIndex + 2; triIndex++; meshTriangles[triIndex] = nextPointIndex; triIndex++; meshTriangles[triIndex] = pointIndex + 1; triIndex++; meshTriangles[triIndex] = nextPointIndex + 1; triIndex++; meshTriangles[triIndex] = pointIndex + 5; triIndex++; meshTriangles[triIndex] = nextPointIndex + 1; triIndex++; meshTriangles[triIndex] = nextPointIndex + 5; triIndex++; meshTriangles[triIndex] = pointIndex + 5; triIndex++; meshTriangles[triIndex] = pointIndex + 3; triIndex++; meshTriangles[triIndex] = pointIndex + 7; triIndex++; meshTriangles[triIndex] = nextPointIndex + 7; triIndex++; meshTriangles[triIndex] = pointIndex + 3; triIndex++; meshTriangles[triIndex] = nextPointIndex + 7; triIndex++; meshTriangles[triIndex] = nextPointIndex + 3; triIndex++; meshTriangles[triIndex] = pointIndex + 4; triIndex++; meshTriangles[triIndex] = nextPointIndex + 4; triIndex++; meshTriangles[triIndex] = pointIndex + 6; triIndex++; meshTriangles[triIndex] = pointIndex + 6; triIndex++; meshTriangles[triIndex] = nextPointIndex + 4; triIndex++; meshTriangles[triIndex] = nextPointIndex + 6; } pointIndex = meshVertices.GetLength(0) - 4; triIndex = meshTriangles.GetLength(0) - 6; meshTriangles[triIndex] = pointIndex; triIndex++; meshTriangles[triIndex] = pointIndex + 1; triIndex++; meshTriangles[triIndex] = pointIndex + 2; triIndex++; meshTriangles[triIndex] = pointIndex + 1; triIndex++; meshTriangles[triIndex] = pointIndex + 3; triIndex++; meshTriangles[triIndex] = pointIndex + 2; this.lineObject.transform.position = Vector3.zero; this.lineObject.transform.rotation = Quaternion.identity; this.lineMesh.Clear(); this.lineMesh.vertices = meshVertices; this.lineMesh.triangles = meshTriangles; this.lineMesh.normals = meshNormals; this.lineMesh.uv = meshUVs; this.lineMesh.colors = meshColors; }
//raycasting and information on visual gathering public void FillVisibilityGrid() //fills the visibility grid with the qualities of view from this camera { //getting coordinates of all ground projections - Floor must have boxcollider Vector3[,,] projectedRays = ProjectRaysFromCamera(); Bounds map = GameObject.Find("Floor").GetComponent <BoxCollider>().bounds; Bounds mapVolume = GameObject.Find("Map").GetComponent <MapController>().mapBounds; Vector3[,] onTheGroundProjections = new Vector3[projectedRays.GetLength(0), projectedRays.GetLength(1)]; for (int i = 0; i < onTheGroundProjections.GetLength(0); i++) { for (int j = 0; j < onTheGroundProjections.GetLength(1); j++) { if (mapVolume.Contains(projectedRays[i, j, 0])) { //Debug.Log(projectedRays[i, j, 0]); onTheGroundProjections[i, j] = map.ClosestPoint(projectedRays[i, j, 0]); } else { onTheGroundProjections[i, j] = Vector3.zero; } } } Cell[,] grid = GameObject.Find("Map").GetComponent <GridController>().observationGrid; //declaring a fictious grid and initializing it, for quality of view of this camera float[,] proposedGrid = new float[grid.GetLength(0), grid.GetLength(1)]; for (int i = 0; i < proposedGrid.GetLength(0); i++) { for (int j = 0; j < proposedGrid.GetLength(1); j++) { proposedGrid[i, j] = 0f; } } GridController pointer = GameObject.Find("Map").GetComponent <GridController>(); //substituting each cell which has a higher QoV from the fictious grid to the actual grid for (int p1 = 0; p1 < onTheGroundProjections.GetLength(0); p1++) { for (int p2 = 0; p2 < onTheGroundProjections.GetLength(1); p2++) { for (int i = 0; i < proposedGrid.GetLength(0); i++) { for (int j = 0; j < proposedGrid.GetLength(1); j++) { if (onTheGroundProjections[p1, p2] != Vector3.zero & grid[i, j].Contains(onTheGroundProjections[p1, p2])) { //proposedGrid[i, j] += SpatialConfidence(projectedRays[p1, p2, 0]); //update the timeConfidenceGridNewObs pointer.UpdateTimeConfidenceGridNewObs(i, j); pointer.UpdateSpatialConfidenceGridNewObs(i, j, SpatialConfidence(projectedRays[p1, p2, 0])); //Debug.Log(onTheGroundProjections[p1, p2]); //Debug.Log(projectedRays[i, j, 1]); if (projectedRays[p1, p2, 1].magnitude > 1) { pointer.CountObservationGridNewObs(i, j); //Debug.Log(i + "," + j); //Debug.Log(projectedRays[i, j, 1].z); } } if (p1 == (onTheGroundProjections.GetLength(0) - 1) && p2 == (onTheGroundProjections.GetLength(1) - 1)) //when I finished projecting every possible projection in this cell set the qualityofview of the grid to be the highest { //Debug.Log(onTheGroundProjections[p1, p2]); if (grid[i, j].value < proposedGrid[i, j]) { grid[i, j].value = proposedGrid[i, j]; } } } } } } }
void Start() { Random.seed = SpawnSeed; mapSort = this.GetComponent<MapSortingScript>(); float Width = 0; float Height = 0; float Depth = 0; if (null != defaultSpawnObject.transform.FindChild("Floor")) { Width = defaultSpawnObject.transform.FindChild("Floor").lossyScale.x; Height = defaultSpawnObject.transform.FindChild("Floor").lossyScale.y; Depth = defaultSpawnObject.transform.FindChild("Floor").lossyScale.z; } else { Width = defaultSpawnObject.transform.localScale.x; Height = defaultSpawnObject.transform.localScale.y; Depth = defaultSpawnObject.transform.localScale.z; } //print("Width=" + Width + " Height=" + Height + " Depth=" + Depth); float MaxWidth = Mathf.Max(spawnSpace[0].transform.position.x, spawnSpace[1].transform.position.x); float MaxHeight = Mathf.Max(spawnSpace[0].transform.position.y, spawnSpace[1].transform.position.y); float MaxDepth = Mathf.Max(spawnSpace[0].transform.position.z, spawnSpace[1].transform.position.z); //print("MaxWidth=" + MaxWidth + " MaxHeight=" + MaxHeight + " MaxDepth=" + MaxDepth); Vector3 StartingVec = Vector3.zero; if (spawnSpace[0].transform.position.x < spawnSpace[1].transform.position.x) StartingVec = spawnSpace[0].transform.position; else StartingVec = spawnSpace[1].transform.position; List<Vector3> spawnWidthPlaces = GetSpawnLocationOnAxis(new Vector3(Width, 0, 0), new Vector3(MaxWidth, MaxHeight, MaxDepth), StartingVec); if (spawnSpace[0].transform.position.y < spawnSpace[1].transform.position.y) StartingVec = spawnSpace[0].transform.position; else StartingVec = spawnSpace[1].transform.position; List<Vector3> spawnHeightPlaces = GetSpawnLocationOnAxis(new Vector3(0, Height, 0), new Vector3(MaxWidth, MaxHeight, MaxDepth), StartingVec); if (spawnSpace[0].transform.position.z < spawnSpace[1].transform.position.z) StartingVec = spawnSpace[0].transform.position; else StartingVec = spawnSpace[1].transform.position; List<Vector3> spawnDepthPlaces = GetSpawnLocationOnAxis(new Vector3(0, 0, Depth), new Vector3(MaxWidth, MaxHeight, MaxDepth), StartingVec); Vector3[,,] RoomSpawnVecs = new Vector3[spawnWidthPlaces.Count, spawnHeightPlaces.Count, spawnDepthPlaces.Count]; for (int i = 0; i < RoomSpawnVecs.GetLength(0); i++) { RoomSpawnVecs[i, 0, 0] = spawnWidthPlaces[i]; } for (int i = 0; i < RoomSpawnVecs.GetLength(1); i++) { RoomSpawnVecs[0, i, 0] = spawnHeightPlaces[i]; } for (int i = 0; i < RoomSpawnVecs.GetLength(2); i++) { RoomSpawnVecs[0, 0, i] = spawnDepthPlaces[i]; } for (int i = 0; i < RoomSpawnVecs.GetLength(0); i++) { for (int j = 0; j < RoomSpawnVecs.GetLength(1); j++) { if (i == 0 && j == 0) { continue; } else { for (int k = 0; k < RoomSpawnVecs.GetLength(2); k++) { if ((i == 0 || j == 0) && k == 0) { continue; } else { RoomSpawnVecs[i, j, k] = new Vector3(MaxWidth, MaxHeight, MaxDepth); RoomSpawnVecs[i, j, k].x = RoomSpawnVecs[i, 0, 0].x; RoomSpawnVecs[i, j, k].y = RoomSpawnVecs[0, j, 0].y; RoomSpawnVecs[i, j, k].z = RoomSpawnVecs[0, 0, k].z; } } } } } foreach (Vector3 vec in RoomSpawnVecs) { int Odds = Random.Range(0, (UseSmallerOdds ? 1000000 : 100)); if (Odds > (UseSmallerOdds ? 1000000 : 100) - OddsOfSpawning) Spawn(vec); } if(SortObjects) { mapSort.SortObjects(SpawnedObjects); } if(DeleteOuterAfterSort) { for (int i = 0; i < SpawnedObjects.Count; i++) { if (SpawnedObjects[i].transform.position.z > Mathf.Max(spawnSpace[0].position.z, spawnSpace[1].position.z) || SpawnedObjects[i].transform.position.x > Mathf.Max(spawnSpace[0].position.x, spawnSpace[1].position.x) || SpawnedObjects[i].transform.position.z < Mathf.Min(spawnSpace[0].position.z, spawnSpace[1].position.z) || SpawnedObjects[i].transform.position.x < Mathf.Min(spawnSpace[0].position.x, spawnSpace[1].position.x) ) { Destroy(SpawnedObjects[i]); SpawnedObjects.RemoveAt(i); i--; } } } if(PushToBuildingManager) { this.GetComponent<BuildingManager>().PassClosestToBuildings(SpawnedObjects); } if (UseCollectables) { this.GetComponent<CollectableManager>().SetUpCollectables(SpawnedObjects); } }
void UpdateVertices() { UnityEngine.Debug.Log("Update Vertices"); Stopwatch sw = new Stopwatch(); sw.Start(); if (dic_VertexForce.Count == 0) { _mesh.vertices = originalVertices; _mesh.RecalculateNormals(); NormalSolver.RecalculateNormals(_mesh, 30); return; } Vector3[,] offsets = new Vector3[Masses.Count, dic_VertexForce.Count]; Dictionary <int, Vector3> .Enumerator it = dic_VertexForce.GetEnumerator(); int forceIdx = 0; while (it.MoveNext()) { int vertexIdx = it.Current.Key; Vector3 force = it.Current.Value; offsets[vertexIdx, forceIdx++] = force; } // 多组质点弹簧遍历 it = dic_VertexForce.GetEnumerator(); Queue <int> masses = new Queue <int> (); HashSet <int> mark = new HashSet <int> (); forceIdx = 0; while (it.MoveNext()) { int vidx_force = it.Current.Key; Vector3 force = it.Current.Value; offsets[vidx_force, forceIdx] = force; masses.Clear(); mark.Clear(); masses.Enqueue(vidx_force); mark.Add(vidx_force); // 一组质点弹簧遍历 while (masses.Count > 0) { int vidx = masses.Dequeue(); Vector3 delta = offsets[vidx, forceIdx]; // 遍历此节点所有链接点 Dictionary <int, float> edge = MassSprings [vidx]; Dictionary <int, float> .Enumerator iter = edge.GetEnumerator(); while (iter.MoveNext()) { int idx = iter.Current.Key; float value = iter.Current.Value; int key = vidx > idx ? vidx | (idx << 16) : (vidx << 16) | idx; if (mark.Contains(key)) { continue; } Vector3 v = delta / (1 + value / kViscosity); if (v.magnitude <= kThresholdZero) { continue; } if (!dic_VertexForce.ContainsKey(idx) && offsets[idx, forceIdx].sqrMagnitude < v.sqrMagnitude) { offsets[idx, forceIdx] = v; masses.Enqueue(idx); } } iter = edge.GetEnumerator(); while (iter.MoveNext()) { int idx = iter.Current.Key; int key = vidx > idx ? vidx | (idx << 16) : (vidx << 16) | idx; mark.Add(key); } } forceIdx++; } sw.Stop(); //UnityEngine.Debug.LogFormat ("using {0}", sw.ElapsedMilliseconds); // 计算各顶点偏移量 for (int i = 0; i < offsets.GetLength(0); i++) { Vector3 result = Vector3.zero; // 计算改顶点最终形变量(x,y,z) for (int j = 0; j < 3; j++) { float positive = 0f; float negative = 0f; for (int k = 0; k < dic_VertexForce.Count; k++) { Vector3 offset = offsets [i, k]; float v = offset [j]; if (v > 0 && v > positive) { positive = v; } else if (v < 0 && v < negative) { negative = v; } } result [j] = positive + negative; } // 最终结果保存在第一个位置 offsets [i, 0] = result; } // 计算出最新的顶点位置 for (int i = 0; i < Masses.Count; i++) { MassPoint mass = Masses [i]; for (int j = 0; j < mass.vertices.Count; j++) { int vid = mass.vertices [j]; displacedVertices [vid] = originalVertices [vid] + offsets [i, 0]; } } _mesh.vertices = displacedVertices; _mesh.RecalculateNormals(); NormalSolver.RecalculateNormals(_mesh, 30); }
/// <summary> /// Instantiate a water plane object based on the current properties of the /// terrain (width, length, and height) /// </summary> void CreateWaterPlane() { // Create the water plane object GameObject waterObject = new GameObject("WaterPlane"); // Create the mesh of the water plane object waterObject.AddComponent <MeshRenderer>(); MeshFilter filter = waterObject.AddComponent <MeshFilter>(); filter.mesh = new Mesh(); // Instantiating required variables #region Water plane instance instantiations int fractionalSize = 4; int relativeResolution; // Relative resolution of water to terrain // Must be two or greater. If not, default relative resolution to two. if (resolution / fractionalSize < 2) { relativeResolution = 2; } // If greater than two, set relative resolution to a fraction of the // full resolution, and round up. else { relativeResolution = Mathf.CeilToInt((float)resolution / fractionalSize); } // Create texture and Perlin shift offset speed (the amount they shift) float xStep = Random.Range(minWaterSpeed, maxWaterSpeed); float zStep = Random.Range(minWaterSpeed, maxWaterSpeed); // Randomly assign x and z shifts to be positive or negative xStep *= (Random.Range(1, 3) * 2 - 3); zStep *= (Random.Range(1, 3) * 2 - 3); // Create a 2D array of vertex coordinates for the water plane object Vector3[,] vertexCoordinates = new Vector3[relativeResolution, relativeResolution]; #endregion // Calculate, store, and assign the vertices for the water plane object // Initial y vertices are determined w/ random Perlin noise-based values #region Vertex Generation Vector3[] vertices = new Vector3[relativeResolution * relativeResolution]; float xPerRes = Width / (relativeResolution - 1); float yPerRes = Length / (relativeResolution - 1); float yStep = Random.Range(.1f, 1f); float xPerlin = 0; float yPerlin = 0; int vertCount = 0; for (int r = 0; r < relativeResolution; r++) { for (int c = 0; c < relativeResolution; c++) { vertexCoordinates[r, c] = new Vector3( (r * xPerRes) - (Width / 2), Mathf.PerlinNoise(xPerlin, yPerlin) * (maxWaterHeight * 2) - (maxWaterHeight / 2), (c * yPerRes) - (Length / 2)); vertices[vertCount] = vertexCoordinates[r, c]; vertCount++; xPerlin += yStep; } xPerlin = 0; yPerlin += yStep; } filter.mesh.vertices = vertices; #endregion yStep = Random.Range(minWaterBob, maxWaterBob); // Set the triangles of the water plane object #region Triangle Generation int[] triangles = new int[(relativeResolution - 1) * (relativeResolution - 1) * 6]; int triCount = 0; for (int r = 0; r < relativeResolution - 1; r++) { for (int c = 0; c < relativeResolution - 1; c++) { // Top side triangles[triCount] = (r * relativeResolution) + c; triangles[triCount + 1] = (r * relativeResolution) + c + 1; triangles[triCount + 2] = ((r + 1) * relativeResolution) + c + 1; triangles[triCount + 3] = ((r + 1) * relativeResolution) + c + 1; triangles[triCount + 4] = ((r + 1) * relativeResolution) + c; triangles[triCount + 5] = (r * relativeResolution) + c; // Bottom side //triangles[triCount + 6] = ((r + 1) * relativeResolution) + c // + 1; //triangles[triCount + 7] = (r * relativeResolution) + c + 1; //triangles[triCount + 8] = (r * relativeResolution) + c; //triangles[triCount + 9] = (r * relativeResolution) + c; //triangles[triCount + 10] = ((r + 1) * relativeResolution) + c; //triangles[triCount + 11] = ((r + 1) * relativeResolution) + c // + 1; triCount += 6; } } filter.mesh.triangles = triangles; #endregion filter.mesh.RecalculateNormals(); // Set the UVs of the water plane object #region UV Generation Vector2[] uvs = new Vector2[vertCount]; int uvCount = 0; for (int r = 0; r < vertexCoordinates.GetLength(0); r++) { for (int c = 0; c < vertexCoordinates.GetLength(1); c++) { uvs[uvCount] = new Vector2( (float)r / vertexCoordinates.GetLength(0), (float)c / vertexCoordinates.GetLength(1)); uvCount++; } } filter.mesh.uv = uvs; #endregion // Assign the water material to the water plane object & scale it waterObject.GetComponent <Renderer>().material = waterMaterial; waterObject.GetComponent <Renderer>().material.mainTextureScale = new Vector2(Width * texturesPerUnit, Length * texturesPerUnit); // Place the water plane object in the center of the terrain at the // specified water height percentage of the maximum height. waterObject.transform.position = new Vector3( (Width / 2) * transform.lossyScale.x + transform.position.x, waterHeightPercentage * terrainData.size.y * transform.lossyScale.y + transform.position.y, (Length / 2) * transform.lossyScale.z + transform.position.z); waterObject.transform.parent = transform; // Add the Perlin noise-based water script to the water plane object #region WaterBehavior Script waterObject.AddComponent <WaterBehavior>(); waterObject.GetComponent <WaterBehavior>().SetVertices(filter.mesh.vertices); waterObject.GetComponent <WaterBehavior>().PlaneSize = new Vector2(vertexCoordinates.GetLength(0), vertexCoordinates.GetLength(1)); waterObject.GetComponent <WaterBehavior>().BobDistance = maxWaterHeight * 2; waterObject.GetComponent <WaterBehavior>().maxFogDistance = maxFogDistance; waterObject.GetComponent <WaterBehavior>().maxFogStrength = maxFogStrength; waterObject.GetComponent <WaterBehavior>().XSpeed = xStep; waterObject.GetComponent <WaterBehavior>().YSpeed = yStep; waterObject.GetComponent <WaterBehavior>().ZSpeed = zStep; waterObject.GetComponent <WaterBehavior>().fpsController = fpsController; #endregion }
public int[] indexOfClosestPointMultiDim(Vector3[,] pointsFrom, Vector3 point) { float[,] sqrMagnitudes = new float[pointsFrom.GetLength(0), pointsFrom.GetLength(1)]; for (int i = 0; i < pointsFrom.GetLength(0); i++) { for (int j = 0; j < pointsFrom.GetLength(1); j++) { sqrMagnitudes[i,j] = ((point.x - pointsFrom[i, j].x) * (point.x - pointsFrom[i, j].x)) + ((point.z - pointsFrom[i, j].z) * (point.z - pointsFrom[i, j].z)); } } return findIndexMinMultiDim(sqrMagnitudes); }
public void InitialiseParticles(Vector3[,] config) { float i, j; //initialise fluid particles from array foreach (var v in config) { Particle p = new Particle(); Vector2 temp = new Vector2(v.X, v.Y); p.Position = temp; p.Oldposition = temp; if (v.Z == 1) p.Mass = 1; plst.Add(p); } //Create four walls for the box box_width = config[config.GetLength(0) - 1, config.GetLength(1) - 1].X + 20; box_height = config[config.GetLength(0) - 1, 0].Y + 15; //initialise base particles for (i = 0; i <= /*256*/box_width; i += 3) for (j = 0; j <= 9; j += 3) { Particle bp = new Particle(); Vector2 temp = new Vector2(i, j); bp.Position = temp; bp.Oldposition = temp; bp.Isstationaryboundary = true; plst.Add(bp); } //initialise left wall particles for (i = 0; i <= 9; i += 3) for (j = 12; j <= /*253*/box_height; j += 3) { Particle mbp = new Particle(); Vector2 temp2 = new Vector2(i, j); mbp.Position = temp2; mbp.Oldposition = temp2; mbp.Ismovingboundary = true; plst.Add(mbp); } //initalise right wall particles for (i = box_width - 10; i <= box_width; i += 3) for (j = 12; j <= box_height; j += 3) { Particle bp = new Particle(); Vector2 temp = new Vector2(i, j); bp.Position = temp; bp.Oldposition = temp; bp.Isstationaryboundary = true; plst.Add(bp); } //initialise top of box for (i = 0; i <= box_width; i += 3) for (j = box_height + 2; j <= box_height + 10; j += 3) { Particle bp = new Particle(); Vector2 temp = new Vector2(i, j); bp.Position = temp; bp.Oldposition = temp; bp.Isstationaryboundary = true; plst.Add(bp); } foreach (Particle p in plst) { p.Vsigma = vsigma; p.Vbeta = vbeta; } }
void BuildPointPath(float[] startPoint, float[] endPoint) { float[] pathPoints = new float[74 * 3]; int pointCount = 0; uint dtResult = Detour.DT_FAILURE; if (_straightLine) { dtResult = Detour.DT_SUCCESS; pointCount = 1; Array.Copy(startPoint, pathPoints, 3); // first point // path has to be split into polygons with dist SMOOTH_PATH_STEP_SIZE between them Vector3 startVec = new Vector3(startPoint[0], startPoint[1], startPoint[2]); Vector3 endVec = new Vector3(endPoint[0], endPoint[1], endPoint[2]); Vector3 diffVec = (endVec - startVec); Vector3 prevVec = startVec; float len = diffVec.GetLength(); diffVec *= 4.0f / len; while (len > 4.0f) { len -= 4.0f; prevVec += diffVec; pathPoints[3 * pointCount + 0] = prevVec.X; pathPoints[3 * pointCount + 1] = prevVec.Y; pathPoints[3 * pointCount + 2] = prevVec.Z; ++pointCount; } Array.Copy(endPoint, 0, pathPoints, 3 * pointCount, 3); // last point ++pointCount; } else if (_useStraightPath) { dtResult = _navMeshQuery.findStraightPath( startPoint, // start position endPoint, // end position _pathPolyRefs, (int)_polyLength, pathPoints, // [out] path corner points null, // [out] flags null, // [out] shortened path ref pointCount, (int)_pointPathLimit, 0); // maximum number of points/polygons to use } else { dtResult = FindSmoothPath( startPoint, // start position endPoint, // end position _pathPolyRefs, // current path _polyLength, // length of current path out pathPoints, // [out] path corner points out pointCount, _pointPathLimit); // maximum number of points } if (pointCount < 2 || Detour.dtStatusFailed(dtResult)) { // only happens if pass bad data to findStraightPath or navmesh is broken // single point paths can be generated here /// @todo check the exact cases Log.outDebug(LogFilter.Maps, "++ PathGenerator.BuildPointPath FAILED! path sized {0} returned\n", pointCount); BuildShortcut(); pathType = PathType.NoPath; return; } else if (pointCount == _pointPathLimit) { Log.outDebug(LogFilter.Maps, "++ PathGenerator.BuildPointPath FAILED! path sized {0} returned, lower than limit set to {1}\n", pointCount, _pointPathLimit); BuildShortcut(); pathType = PathType.Short; return; } _pathPoints = new Vector3[pointCount]; for (uint i = 0; i < pointCount; ++i) { _pathPoints[i] = new Vector3(pathPoints[i * 3 + 2], pathPoints[i * 3], pathPoints[i * 3 + 1]); } NormalizePath(); // first point is always our current location - we need the next one SetActualEndPosition(_pathPoints[pointCount - 1]); // force the given destination, if needed if (_forceDestination && (!pathType.HasAnyFlag(PathType.Normal) || !InRange(GetEndPosition(), GetActualEndPosition(), 1.0f, 1.0f))) { // we may want to keep partial subpath if (Dist3DSqr(GetActualEndPosition(), GetEndPosition()) < 0.3f * Dist3DSqr(GetStartPosition(), GetEndPosition())) { SetActualEndPosition(GetEndPosition()); _pathPoints[_pathPoints.Length - 1] = GetEndPosition(); } else { SetActualEndPosition(GetEndPosition()); BuildShortcut(); } pathType = (PathType.Normal | PathType.NotUsingPath); } Log.outDebug(LogFilter.Maps, "PathGenerator.BuildPointPath path type {0} size {1} poly-size {2}\n", pathType, pointCount, _polyLength); }
void ReadBinaryFile(string fileName, PDSData data) { _imgData = File.ReadAllBytes(Path.Combine(Application.streamingAssetsPath, $"{fileName}.IMG")); float[] floatData = new float[_imgData.Length / 4]; float[,] floatDataDimensional = new float[data.ColumnCount, data.RowCount]; for (int y = 0; y < data.RowCount; y++) { for (int x = 0; x < data.ColumnCount; x++) { var i = x + Width * y; floatData[i] = BitConverter.ToSingle(_imgData, i * 4); floatDataDimensional[x, y] = floatData[i]; } } var min = floatData.Min(); var max = floatData.Max(); print($"min: {min}, max: {max}"); if (DrawTexture) { renderer.sharedMaterial = new Material(Shader.Find("Standard")); _texture = new Texture2D(data.ColumnCount, data.RowCount, TextureFormat.RGBA32, false); for (var y = 0; y < data.RowCount; y++) { for (var x = 0; x < data.ColumnCount; x++) { byte c = (byte)RemapValue(floatDataDimensional[x, y], min, max, 0, 255); var color = new Color32(c, c, c, 255); _texture.SetPixel(x, y, color, 0); } } _texture.Apply(); renderer.sharedMaterial.mainTexture = _texture; } if (DrawMesh) { var verts = new Vector3[data.ColumnCount, data.RowCount]; print($"width: {verts.GetLength(0)}"); print($"height: {verts.GetLength(1)}"); Assert.AreEqual(verts.GetLength(0), Width); Assert.AreEqual(verts.GetLength(1), Height); for (var y = 0; y < data.RowCount; y++) { for (var x = 0; x < data.ColumnCount; x++) { float z = RemapValue(floatDataDimensional[x, data.RowCount - 1 - y], min, max, MoonConstants.LowestPointOnTheMoon, MoonConstants.HighestPointOnTheMoon); verts[x, y] = (new Vector3(x, z, -y) + new Vector3(-data.ColumnCount / 2f, 0, data.RowCount / 2f)) * (Radius * 2f / data.RowCount); } } var mf = GetComponent <MeshFilter>(); var mr = GetComponent <MeshRenderer>(); if (!DrawTexture) { mr.material = MoonMaterial; } var d = SphereMeshGenerator.GenerateTerrainMesh(verts); var mesh = d.CreateMesh32Bit(); mesh = FlipMesh(mesh); mf.sharedMesh = mesh; } if (DrawChunk) { var verts = new Vector3[Height, Height]; for (int i = 0; i < 2; i++) { for (var y = 0; y < data.RowCount; y++) { for (var x = 0; x < data.ColumnCount / 2; x++) { var offset = i * Height; float z = RemapValue(floatDataDimensional[x + offset, data.RowCount - 1 - y], min, max, MoonConstants.LowestPointOnTheMoon, MoonConstants.HighestPointOnTheMoon); verts[x, y] = (new Vector3(x + offset, z, -y) + new Vector3(-data.ColumnCount / 2f, 0, data.RowCount / 2f)) * (Radius * 2f / data.RowCount); } } if (i == 0) { var a = SphereMeshGenerator.GenerateTerrainMesh(verts); var mesh = a.CreateMesh32Bit(); mesh = FlipMesh(mesh); meshA.sharedMesh = mesh; } else { var b = SphereMeshGenerator.GenerateTerrainMesh(verts); var mesh = b.CreateMesh32Bit(); mesh = FlipMesh(mesh); meshB.sharedMesh = mesh; } } } }
void updateVertices(Vector3[] vert) { Release (); // reallocate buffers ans stuff <3 UnityEngine.Debug.Log ("This should not be called twice!!"); mCount = vert.GetLength(0); // allocate buffer for computeShader /* buffer = new ComputeBuffer(mCount, sizeof(float)*3, ComputeBufferType.Default); normal = new ComputeBuffer(mCount, sizeof(float)*3, ComputeBufferType.Default); normalGenerated = new ComputeBuffer(mCount, sizeof(float)*3, ComputeBufferType.Default); tangent = new ComputeBuffer(mCount, sizeof(float)*3, ComputeBufferType.Default); debugColor = new ComputeBuffer(mCount, sizeof(float)*3, ComputeBufferType.Default); // holds the infered crater generatedBuffer = new ComputeBuffer(mCount, sizeof(float)*3, ComputeBufferType.Default); iteratorCount = new ComputeBuffer(mCount, sizeof(int), ComputeBufferType.Default); error = new ComputeBuffer(mCount, sizeof(float), ComputeBufferType.Default); SAD = new ComputeBuffer(numGroups, sizeof(float), ComputeBufferType.Default); SADArray = new float[numGroups]; SetBuffer ("buffer", buffer); SetBuffer ("_normal", normal); SetBuffer ("_normalGenerated", normalGenerated); SetBuffer ("_tangent", tangent); SetBuffer ("debugColor", debugColor); SetBuffer ("generatedBuffer", generatedBuffer); SetBuffer ("iteratorCount", iteratorCount); SADShader.SetBuffer (SADKernel,"SAD", SAD); SADShader.SetBuffer(SADKernel,"error", error); UnityEngine.Debug.LogFormat ("Total verts, "+mCount); // copy points to gpu buffer.SetData(vert); // CCI.onGeometryUpdate (); */ }
public Vector3[,,] ProjectRaysFromCamera() //returns a matrix with information about what rays coming out of the camera see { int layermask = 1 << 9; layermask = ~layermask; //layermask that lets me hit everything, needed because of how I call raycast float height, width, fractionaryHeight, fractionaryWidth; height = Mathf.Tan(vFOV / 2f * Mathf.Deg2Rad) * 2f; width = Mathf.Tan(FOV / 2f * Mathf.Deg2Rad) * 2f; fractionaryHeight = height / (cameraHeight / downscalingFactor); fractionaryWidth = width / (cameraWidth / downscalingFactor); Vector3 rectangleCenter = transform.position + transform.forward; Vector3[,,] res = new Vector3[(int)Mathf.Round(cameraHeight / downscalingFactor) + 1, (int)Mathf.Round(cameraWidth / downscalingFactor) + 1, 2]; //the +1 is needed to cover the whole FOV area without leaving the last fractionary portion out for (int i = 0; i < res.GetLength(0); i++) { for (int j = 0; j < res.GetLength(1); j++) { RaycastHit hit; Vector3 destinationPoint; if (i % 2 == 0 || j == res.GetLength(1) - 1 || j == 0) { destinationPoint = (rectangleCenter - transform.right * width / 2f + transform.up * height / 2f) + i * fractionaryHeight * (-transform.up) + j * fractionaryWidth * transform.right; } else { //spread the rays in alternating rows, so that I can effectively cover double the space horizontally destinationPoint = (rectangleCenter - transform.right * width / 2f + transform.up * height / 2f + (fractionaryWidth / 2f) * transform.right) + i * fractionaryHeight * (-transform.up) + j * fractionaryWidth * transform.right; } Ray ray = new Ray(transform.position, destinationPoint - transform.position); if (Physics.Raycast(ray, out hit, maxDistance, layermask)) { res[i, j, 0] = hit.point; //check if the person can be detected (check distance if it's close enough I'll detect it) if (hit.transform.tag == "Person") { // check is face is big enough to be detected // check if person already detected //Debug.Log(res[i, j, 1]); //add //hit.transform.GetComponent<Person>().PersonID; //hit.transform.GetChild(1).transform; //Debug.Log(hit.transform.name); //Debug.Log(hit.transform.GetChild(2).GetChild(0).GetChild(0).GetChild(0).GetChild(0).GetChild(1).GetChild(0).GetChild(0).GetChild(1).name); //Neckadjust //Debug.Log(hit.transform.GetChild(2).GetChild(0).GetChild(0).GetChild(0).GetChild(0).GetChild(1).GetChild(0).GetChild(0).GetChild(0).GetChild(14).name); //Nosetop //Debug.Log(this.GetComponent<Camera>().WorldToScreenPoint(hit.transform.GetChild(2).GetChild(0).GetChild(0).GetChild(0).GetChild(0).GetChild(1).GetChild(0).GetChild(0).GetChild(1).position)); //Debug.Log(this.GetComponent<Camera>().WorldToScreenPoint(hit.transform.GetChild(2).GetChild(0).GetChild(0).GetChild(0).GetChild(0).GetChild(1).GetChild(0).GetChild(0).GetChild(0).GetChild(14).position)); //test = GUIRectWithObject(hit.transform.gameObject); //test = BoundsToScreenRect(hit.transform.gameObject.GetComponent<Collider>().bounds); //Debug.Log(hit.transform.gameObject); if (personHit.Contains(hit.transform.gameObject) != true) { personHit.Add(hit.transform.gameObject); //Debug.Log(hit.transform.gameObject.name); //res[i, j, 1] = new Vector3(1, 1, res[i, j, 1].z + 1); Bounds b = hit.transform.GetChild(3).GetComponent <Renderer>().bounds; //Debug.Log(b); //Debug.Log(cam); //The object is behind us if (cam.WorldToScreenPoint(b.center).z < 0) { continue; } //All 8 vertices of the bounds pts[0] = cam.WorldToScreenPoint(new Vector3(b.center.x + b.extents.x, b.center.y + b.extents.y, b.center.z + b.extents.z)); pts[1] = cam.WorldToScreenPoint(new Vector3(b.center.x + b.extents.x, b.center.y + b.extents.y, b.center.z - b.extents.z)); pts[2] = cam.WorldToScreenPoint(new Vector3(b.center.x + b.extents.x, b.center.y - b.extents.y, b.center.z + b.extents.z)); pts[3] = cam.WorldToScreenPoint(new Vector3(b.center.x + b.extents.x, b.center.y - b.extents.y, b.center.z - b.extents.z)); pts[4] = cam.WorldToScreenPoint(new Vector3(b.center.x - b.extents.x, b.center.y + b.extents.y, b.center.z + b.extents.z)); pts[5] = cam.WorldToScreenPoint(new Vector3(b.center.x - b.extents.x, b.center.y + b.extents.y, b.center.z - b.extents.z)); pts[6] = cam.WorldToScreenPoint(new Vector3(b.center.x - b.extents.x, b.center.y - b.extents.y, b.center.z + b.extents.z)); pts[7] = cam.WorldToScreenPoint(new Vector3(b.center.x - b.extents.x, b.center.y - b.extents.y, b.center.z - b.extents.z)); //Get them in GUI space for (int ii = 0; ii < pts.Length; ii++) { pts[ii].y = Screen.height - pts[ii].y; } //Calculate the min and max positions Vector3 min = pts[0]; Vector3 max = pts[0]; for (int ii = 1; ii < pts.Length; ii++) { min = Vector3.Min(min, pts[ii]); max = Vector3.Max(max, pts[ii]); } //Construct a rect of the min and max positions and apply some margin test = Rect.MinMaxRect(min.x, min.y, max.x, max.y); test.xMin -= margin; test.xMax += margin; test.yMin -= margin; test.yMax += margin; if (test.height > 25 && test.width > 25) { personHitSizeChecked.Add(hit.transform.gameObject); boundingBoxes.Add(test); res[i, j, 1] = new Vector3(1, 1, 1); if (GameObject.Find("Map").GetComponent <GridController> ().people.Contains(hit.transform.gameObject) != true) { GameObject.Find("Map").GetComponent <GridController>().people.Add(hit.transform.gameObject); } } } } //else //{ // res[i, j, 1] = new Vector3(0, 0, 0); //} Debug.DrawLine(transform.position, hit.point); } } } return(res); }
/// <summary> /// 弾丸を発射する /// </summary> public void Enter(bool isTestScene = false) { isTest = isTestScene; if (abnState == null) { bulletObj = Instantiate(prefab.GetComponent <Bullet>().bulletObj, transform); if (!bulletObj.GetComponent <BulletObject>()) { BulletObject bulObj = bulletObj.AddComponent <BulletObject>(); bulObj.parent = this; } } else { ChangeElement(abnState); } //弾道を自身の子にする //bulletObj.transform.SetParent(transform); //bulletObj.transform.localPosition = GetDefaultPos (); ReturnToDefaultPos(); switch (bulletType) { case BulletType.beam: StartCoroutine(WaitShotEndTime(moveTime)); break; case BulletType.fixe: StartCoroutine(WaitShotEndTime(moveTime)); //StartCoroutine(WaitShotEndTime(moveTime)); RotateBullet rotate = bulletObj.AddComponent <RotateBullet>(); rotate.SetTarget(GameObject.FindGameObjectWithTag(Tags.Player)); rotate.speed = 600; rotate.SetTime(moveTime); break; default: Hashtable hash = new Hashtable(); switch (movePath.GetLength(0)) { case 0: Debug.LogAssertion("経路が設定されていません"); return; case 1: hash.Add("position", transform.position + Rotate(movePath[0])); break; default: Vector3[] path = new Vector3[movePath.Length]; for (int i = 0; i < path.GetLength(0); i++) { path[i] = transform.position + Rotate(movePath[i]); } hash.Add("path", path); break; } hash.Add("time", moveTime); hash.Add("easetype", type); hash.Add("oncompletetarget", gameObject); hash.Add("oncomplete", "MoveEnd"); iTween.MoveTo(bulletObj, hash); //弾道を親から外す bulletObj.transform.parent = null; break; } switch (bulletType) { case BulletType.beam: break; default: //経路予測線を消去 DeleteDrawLine(); //if (!isDraw) if (isTest) { StartCoroutine(MovePathDraw()); } break; } bulletObj.GetComponent <BulletObject>().ShotStart(); if (pairBullet) { pairBullet.Enter(isTestScene); } }
private void OpenGLControl_OpenGLDraw(object sender, SharpGL.SceneGraph.OpenGLEventArgs args) { Title = "basketball-game"; OpenGL gl = args.OpenGL; gl.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT); RenderColor(gl); Render3D(gl); gl.LoadIdentity(); //Manipulate Camera gl.LookAt(0 - mouseVector.x - movementVector.x, 0 + mouseVector.y - movementVector.y, 20.0f + zoom, 0 - movementVector.x, 0 + mouseVector.y, zoom, 0, 1, 0); //Then Translate gl.Translate(0.0f, 10.0f, -50.0f); //Draw 3D Objects #region Draw 3D Objects Ball.DrawBasketBall(gl, 60, 0, 0, 0); Ground.DrawCube(gl, 0, 120, 0); Pole.DrawCube(gl, 100, 100, 100); Board.DrawCube(gl, 0, 200, 200); RingEdge.DrawCube(gl, 0, 200, 200); RimNet.Draw(gl, 50, 50, 50); CenNet.Draw(gl, 40, 40, 40); //simulatedBall.DrawCircle(gl, 1); //Aiming Line Draw if (showLine) { if (isBallThrown) { //Line.DrawLine(gl, Ball, Ball.Velocity, 1, 200, 60, 60); Line.DrawSimulatedPath(gl, Ball, Ball.Velocity, 1, 200, 60, 60); } else { //Line.DrawLine(gl, Ball, modifierVector, 1, 200, 60, 60); Line2.DrawSimulatedPath(gl, simulatedBall, simulatedVector, 1, 200, 0, 0); } } //End Drawing Most 3D Objects #endregion #region Draw Text var angle = (Math.Truncate((Math.Atan(modifierVector.y / modifierVector.x) * 180 / Math.PI) * 100.0) / 100.0); //Above gl.DrawText(5, 630, 1, 0, 0, "Arial", 15, "Round: " + curRound); gl.DrawText(5, 600, 1, 0, 0, "Arial", 30, "Score: " + curScore); gl.DrawText(5, 570, 1, 0, 0, "Arial", 20, "Camera Movement Enabled: " + Keyboard.IsKeyToggled(toggleMovementKey).ToString()); gl.DrawText(5, 480, 1, 0, 0, "Arial", 30, gameStage); //Below gl.DrawText(230, 20, 1, 0, 0, "Arial", 15, "Angle: " + angle); gl.DrawText(400, 5, 1, 0, 0, "Arial", 15, "Increments: " + increments); gl.DrawText(400, 20, 1, 0, 0, "Arial", 15, "Power: " + power); gl.DrawText(900, 20, 1, 0, 0, "Arial", 15, "Reset in: " + curCounter); #endregion showBall.Rotation += 5; #region WINDY Score when > 10 //WINDY!!!!!!!!!!!!!! --- SCORE > 10 if (curScore >= 10) { isWindy = true; gameStage = "It's a bit windy"; ObjectMesh Leave = new ObjectMesh() { Scale = new Vector3(0.5f, 0.5f, 0), Mass = 0.3f }; leaveRandGaussian = (float)Randomizer.Gaussian(-0, 10); leaveRandNorm = (float)Randomizer.Generate(0.1f, 0.5f); Leave.Position = new Vector3(leaveRandGaussian + 150, leaveRandGaussian, 30); Leave.Mass = leaveRandNorm; Leaves.Add(Leave); foreach (var leaf in Leaves) { leaf.DrawCube(gl, 0, 60, 0); leaf.ApplyGravity(); leaf.ApplyForce(rightWindVector); leaf.Velocity.Clamp(-0.2f, -0.2f, 0); if (leaf.HasCollidedWith(Ground)) { leaf.Position.y = Ground.Position.y + Ground.Scale.y + leaf.Scale.y; leaf.Velocity.y = (-(leaf.Velocity.y)); leaf.ApplyFriction(); } else { leaf.ApplyGravity(); leaf.ApplyFriction(); } } } #endregion #region Meteor Fell Score When > 20 if ((curScore >= 20) && (enabledMetoer)) { gameStage = "Some kind of meteor..."; Meteor.DrawCircle(gl); Meteor.ApplyForce(meteorFallingVector); if (Meteor.Position.y <= -30) { Meteor.Velocity.y *= 0; Meteor.Position.y = -30; isMeteorFall = true; } } #endregion #region Ball Thrown Code //You pressed Space if (isBallThrown) { curCounter--; if (curCounter > maxCounter - 2) { Ball.Velocity = modifierVector / 1.5f; } Ball.Rotation += 10; } #endregion #region Scoring if (CenNet.Contains(Ball)) { Console.WriteLine("Ball is in CenNet..."); if (!isScored) { curScore++; randNorm = (float)Randomizer.Generate(-10, 10); randGaussian = (float)Randomizer.Gaussian(1, 2); Console.WriteLine("Player Scores!"); isScored = true; } Ball.ApplyForce(RimNet.CalculateDragForce(Ball) * 1); Ball.ApplyForce(CenNet.CalculateDragForce(Ball) * 2); } #endregion #region Reset Code if (curCounter < 0) { Pole.Position.x += randNorm; Board.Position.x += randNorm; RingEdge.Position.x += randNorm; RimNet.x += randNorm; CenNet.x += randNorm; if ((randNorm < 1) && (randNorm > -1)) { Board.Position.y += randGaussian; RimNet.y += randGaussian; CenNet.y += randGaussian; RingEdge.Position.y += randGaussian; } if ((Pole.Position.x > 70) || (Pole.Position.x < 30)) { Pole.Position.x = 50; Board.Position.x = 48.5f; RingEdge.Position.x = 42.5f; RimNet.x = 45.5f; CenNet.x = 45.5f; } curCounter = maxCounter; isScored = false; curRound++; } if (curCounter == maxCounter) { //isSpaceHeld = false; isBallThrown = false; Ball.Velocity.x *= 0.0f; Ball.Velocity.y *= 0.0f; Ball.Position = BallDefaultPos; randNorm *= 0; randGaussian *= 0; isScored = false; } #endregion #region Controls // These controls only available when Ball is not yet thrown if (!isBallThrown) { //Increment Adjuster if (Keyboard.IsKeyDown(increaseKey) && !Keyboard.IsKeyToggled(toggleMovementKey)) { increments -= 0.1f; } else if (Keyboard.IsKeyDown(decreaseKey) && !Keyboard.IsKeyToggled(toggleMovementKey)) { increments += 0.2f; } increments = GameUtils.Constrain(increments, minIncrements, maxIncrements); //Adjust Power and Angle modified by Increments lineLength = modifierVector.GetLength(); power = (Math.Truncate(lineLength * 100.0) / 100.0); power *= 10; if (Keyboard.IsKeyDown(upKey) && (power < 100) && !Keyboard.IsKeyToggled(toggleMovementKey)) { aimAngle = Math.Atan((modifierVector.y) / (modifierVector.x)); modifierVector.x += increments * (float)Math.Cos(aimAngle); modifierVector.y += increments * (float)Math.Sin(aimAngle); } if (Keyboard.IsKeyDown(downKey) && (power > 10) && !Keyboard.IsKeyToggled(toggleMovementKey)) { aimAngle = Math.Atan((modifierVector.y) / (modifierVector.x)); modifierVector.x -= increments * (float)Math.Cos(aimAngle); modifierVector.y -= increments * (float)Math.Sin(aimAngle); } if (Keyboard.IsKeyDown(rightKey) && !Keyboard.IsKeyToggled(toggleMovementKey)) { aimAngle = Math.Atan(modifierVector.y / modifierVector.x); aimAngle -= (Math.PI / 180) + ((Math.PI / 90) * increments); modifierVector.x = lineLength * (float)Math.Cos(aimAngle); modifierVector.y = lineLength * (float)Math.Sin(aimAngle); } if (Keyboard.IsKeyDown(leftKey) && !Keyboard.IsKeyToggled(toggleMovementKey)) { aimAngle = Math.Atan(modifierVector.y / modifierVector.x); aimAngle += (Math.PI / 180) + ((Math.PI / 90) * increments); modifierVector.x = lineLength * (float)Math.Cos(aimAngle); modifierVector.y = lineLength * (float)Math.Sin(aimAngle); } } //Play Ball if (Keyboard.IsKeyDown(shootKey)) { isBallThrown = true; } //Restart if (Keyboard.IsKeyDown(resetKey) && (curCounter < maxCounter)) { curCounter = -2; } if (Keyboard.IsKeyToggled(toggleLineKey)) { showLine = false; isDrawSimulatedPath = false; } else { showLine = true; isDrawSimulatedPath = true; } //Force Random if (Keyboard.IsKeyDown(randomizeKey)) { randNorm = (float)Randomizer.Generate(-10, 10); randGaussian = (float)Randomizer.Gaussian(1, 2); curCounter = -2; } //Add Score Cheat if (Keyboard.IsKeyDown(cheatKey)) { randNorm = (float)Randomizer.Generate(-10, 10); randGaussian = (float)Randomizer.Gaussian(1, 2); curCounter = -2; curScore++; } if (Keyboard.IsKeyToggled(toggleMovementKey)) { mouseVector = new Vector3(mousePos.x / (50 * (1 / sensitivity)), mousePos.y / (30 * (1 / sensitivity)), 0); eyex = 0 - mouseVector.x + movementVector.x; eyey = 0 + mouseVector.y - movementVector.y; eyez += zoom; cenx = 0 - movementVector.x; ceny = 0 + mouseVector.y; cenz = zoom; if (Keyboard.IsKeyDown(increaseKey)) { zoom += 1; } if (Keyboard.IsKeyDown(decreaseKey)) { zoom -= 1; } if (Keyboard.IsKeyDown(upKey)) { //movementVector.y -= 1; zoom -= 1; } if (Keyboard.IsKeyDown(downKey)) { //movementVector.y -= -1; zoom += 1; } if (Keyboard.IsKeyDown(leftKey)) { movementVector.x -= -1; } if (Keyboard.IsKeyDown(rightKey)) { movementVector.x -= 1; } } if (Keyboard.IsKeyDown(quitKey)) { Environment.Exit(0); } #endregion #region Physics and Collision //Simulated Ball //Main Ball if (Ball.HasCollidedWith(Ground)) { Ball.Velocity.y = (-(Ball.Velocity.y) / 2); Ball.Position.y = Ground.Position.y + Ground.Scale.y + Ball.Radius; Ball.ApplyFriction(); if (isWindy) { Ball.ApplyForce(rightWindVector); } if (isMeteorFall) { Ball.ApplyForce(Meteor.CalculateAttraction(Ball)); } } else { Ball.ApplyGravity(0.2f); Ball.ApplyFriction(); if (isWindy == true) { Ball.ApplyForce(rightWindVector); } if (isMeteorFall == true) { Ball.ApplyForce(Meteor.CalculateAttraction(Ball)); } } if (Ball.HasCollidedWith(Board)) { if (Ball.Position.y > Board.Position.y + Board.Scale.y) { Ball.Velocity.y = (-(Ball.Velocity.y) / 2); } Ball.Velocity.x = (-(Ball.Velocity.x) / 1.5f); } //Ball Collided with Meteor //Get distance between Ball and Metoer then check against its scale if (GameUtils.GetDistanceBetween(Meteor, Ball) < (Ball.Radius + Meteor.Radius) + 2.0f) { Ball.Velocity.x = (-(Ball.Velocity.x) / 1.5f); Ball.Velocity.y = (-(Ball.Velocity.y) / 1.5f); } if (Ball.HasCollidedWith(RingEdge)) { if (Ball.Position.y > RingEdge.Position.y + RingEdge.Scale.y) { Ball.Velocity.y = (-(Ball.Velocity.y) / 2); } Ball.Velocity.x = (-(Ball.Velocity.x) / 1.5f); } if (Ball.HasCollidedWith(Pole)) { Ball.Velocity.x = (-(Ball.Velocity.x) / 1.5f); } #endregion }