void OnSceneGUI() { _spline = target as BezierSpline; _splineT = _spline.transform; _splineR = Tools.pivotRotation == PivotRotation.Local ? _splineT.rotation : Quaternion.identity; // Draw curves Vector3 p0 = ShowPoint(0); for (int i = 1; i < _spline.ControlPointCount; i += 3) { Vector3 p1 = ShowPoint(i); Vector3 p2 = ShowPoint(i + 1); Vector3 p3 = ShowPoint(i + 2); Handles.color = Color.gray; Handles.DrawLine(p0, p1); Handles.DrawLine(p2, p3); Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 2f); p0 = p3; } // Show velocity if(_spline.showVelocity) { Vector3 lineStart = _spline.GetPoint(0f); Handles.color = Color.green; Handles.DrawLine(lineStart, lineStart + _spline.GetDirection(0f)); int steps = _spline.numIterations * _spline.CurveCount; for (int i = 1; i <= steps; i++) { Vector3 lineEnd = _spline.GetPoint(i / (float)steps); Handles.DrawLine(lineEnd, lineEnd + _spline.GetDirection(i / (float)steps)); } } }
public Mesh ExtrudeAlong(BezierSpline spline, Vector3 down) { MeshBuilder meshBuilder = new MeshBuilder(); meshBuilder.BeforeNext(Matrix4x4.identity, new Vector3()); Vector3 lastTangent = spline.GetFirstDerivative(0, spline.pts[0]); Quaternion quat = Quaternion.LookRotation(lastTangent, -down); Vector3 up = down; Vertex[] lastVerts = null; for(int i = 0; i < spline.pts.Length; i ++) { BezierSpline.BezierPoint pt = spline.pts[i]; if (Vector3.Distance(pt.startPos, pt.endPos) > 0.001f) { int subdivisions = pt.numSubdivisions; for (int div = 0; div <= subdivisions; div++) { float t = div / (float)pt.numSubdivisions; Vector3 ptT = spline.GetPoint(t, pt); Vector3 tangent = spline.GetFirstDerivative(t, pt).normalized; quat = Quaternion.FromToRotation(lastTangent, tangent) * quat; lastVerts = BuildNextSection(meshBuilder, ptT, tangent, quat, lastVerts); lastTangent = tangent; } } } AddCap(meshBuilder, new Vector3[] { lastVerts[0].position, lastVerts[2].position, lastVerts[4].position, lastVerts[6].position }, true); return meshBuilder.DoneCreateMesh(); }
public void Initialize() { GuyManager.RegisterGuy( this ); BezierSpline[] splines = FindObjectsOfType<BezierSpline>(); _bezierSpline = splines[ Random.Range( 0, splines.Length ) ]; collider2D.enabled = true; rigidbody2D.isKinematic = true; transform.position = _bezierSpline.GetPoint( 0f ); _appliedMoveSpeed = _catchupSpeed; _percentAlongSpline = 0f; enabled = true; }
private void Awake() { if (frequency <= 0 || items == null || items.Length == 0) { return; } float stepSize = 1f / (frequency * items.Length); for (int p = 0, f = 0; f < frequency; f++) { for (int i = 0; i < items.Length; i++, p++) { Transform item = Instantiate(items[i]) as Transform; Vector3 position = spline.GetPoint(p * stepSize); item.transform.localPosition = position; if (lookForward) { item.transform.LookAt(position + spline.GetDirection(p * stepSize)); } item.transform.parent = transform; } } }
private void Update() { if (startMovement) { progress += Time.deltaTime / pathDuration; Vector3 position = spline.GetPoint(curvePath.Evaluate(progress)); cam.transform.localPosition = position; Vector3 lookAt = position + spline.GetDirection(curvePath.Evaluate(progress)); if (refFollow) { reference.transform.LookAt(lookAt); } RelocateCamera(lookAt); if (progress > 1f) { EndOfPath(); } } }
private void ShowWorldVectors() { int steps = stepsPerCurve * spline.CurveCount; for (int i = 0; i <= steps; i++) { float step = i / (float)steps; Vector3 point = spline.GetPoint(step); Handles.color = Color.red; Vector3 tangent = spline.GetTangent(step); Handles.DrawLine(point, point + tangent * worldVectorsScale); Handles.color = Color.blue; Vector3 binormal = spline.GetBinormal(step); Handles.DrawLine(point, point + binormal * worldVectorsScale); Handles.color = Color.green; Vector3 normal = spline.GetNormal(step); Handles.DrawLine(point, point + normal * worldVectorsScale); } }
private void Awake() { if (frequency <= 0 || items == null || items.Length == 0) { return; } float stepSize = frequency * items.Length; if (spline.Loop || stepSize == 1) { stepSize = 1f / stepSize; } else { stepSize = 1f / (stepSize - 1); } for (int p = 0, f = 0; f < frequency; f++) { for (int i = 0; i < items.Length; i++, p++) { Transform item = Instantiate(items [i]) as Transform; //custom walker = item.GetComponent <SplineWalker>(); walker.spline = spline; //Spaceing along the bezier: f is incrementor, Don't devide by zero!!!! item.GetComponent <SplineWalker>().progress = 1f / (frequency * (items.Length + 1)) * f; Debug.Log("f" + f.ToString() + " is " + (stepSize * f).ToString()); //Vector3 position = spline.GetPoint (p * stepSize); //item.transform.localPosition = position; if (lookForward) { item.transform.LookAt(spline.GetPoint(p * stepSize) + spline.GetDirection(p * stepSize)); } walker = null; } } }
public virtual void FixedUpdate() { if (goingForward) { progress += Time.deltaTime / duration; if (progress > 1f) { if (mode == SplineWalkerMode.Once) { progress = 1f; } else if (mode == SplineWalkerMode.Loop) { LoopWalker(); } else { progress = 2f - progress; goingForward = false; } } } else { progress -= Time.deltaTime / duration; if (progress < 0f) { progress = -progress; goingForward = true; } } Vector3 position = Spline.GetPoint(progress) + offset; SetPosition(position); //transform.LookAt(position + Spline.GetDirection(progress)); }
private void Update() { if (independentDeltaTime) { deltaTime = Time.realtimeSinceStartup - lastTime; } else { deltaTime = Time.deltaTime; } lastTime = Time.realtimeSinceStartup; if (goingForward) { progress += deltaTime / duration; if (progress > 1f) { progress = 1f; } } else { progress -= deltaTime / duration; if (progress < 0f) { progress = 0f; } } Vector3 position = spline.GetPoint(spline.getTByLength(progress)); transform.localPosition = position; if (lookForward) { transform.LookAt(position + spline.GetDirection(progress)); } }
private void Awake() { if (Frequency <= 0 || Items == null || Items.Length == 0) { return; } var stepSize = (float)(Frequency * Items.Length); if (Spline.Loop || stepSize == 1) { stepSize = 1f / stepSize; } else { stepSize = 1f / (stepSize - 1); } for (int p = 0, f = 0; f < Frequency; f++) { for (var i = 0; i < Items.Length; i++, p++) { var item = Instantiate(Items[i]) as Transform; var position = Spline.GetPoint(p * stepSize); item.transform.localPosition = position; if (LookForward) { item.transform.LookAt(position + Spline.GetDirection(p * stepSize)); } item.transform.parent = transform; } } }
// Move every frame, if movement is enabled private void Update() { if (!moving) { return; } progress += Time.deltaTime / duration; if (progress > 1f) { progress = 1f; moving = false; Destroy(spline.gameObject); } Vector3 position = spline.GetPoint(progress); transform.localPosition = position; if (lookForward) { transform.LookAt(position + spline.GetDirection(progress)); } }
// Update is called once per frame void Update() { if (goingForward) { progress += Time.deltaTime / duration; if (progress > 1f) { if (mode == SplineWalkerMode.Once) { progress = 1f; } else if (mode == SplineWalkerMode.Loop) { progress -= 1f; } else { progress = 2f - progress; goingForward = false; } } } else { progress -= Time.deltaTime / duration; if (progress < 0f) { progress = -progress; goingForward = true; } } transform.localPosition = spline.GetPoint(progress); }
private void Awake() { if (frequency <= 0 || items == null || items.Length == 0) { return; } /* This works well for loops, but it doesn't go all the way to the end of splines that aren't loops. * We can fix this by increasing our step size to cover the entire length of the spline, * as long as it's not a loop and we have more than one item to place. */ float stepSize = frequency * items.Length; if (spline.Loop || stepSize == 1) { stepSize = 1f / stepSize; } else { stepSize = 1f / (stepSize - 1); } for (int p = 0, f = 0; f < frequency; f++) { for (int i = 0; i < items.Length; i++, p++) { Transform item = Instantiate(items[i]) as Transform; Vector3 position = spline.GetPoint(p * stepSize); item.transform.localPosition = position; if (lookForward) { item.transform.LookAt(position + spline.GetDirection(p * stepSize)); } item.transform.parent = transform; } } }
private void UpdateSampleTextures() { BezierSpline spline = GetComponent <BezierSpline>(); var splinePixels = new Color[1024]; var curvePixels = new Color[1024]; var initialSpawnDuration = initialSpawnRate.keys[initialSpawnRate.length - 1].time; for (int i = 0; i < 1024; i++) { // R channel - mass distribution float r = mass.Evaluate(i / 1024.0f); // G channel - TTL distribution float g = TTL.Evaluate(i / 1024.0f); // B channel - Spawn rate distribution float b = initialSpawnRate.Evaluate(i / 1024.0f * initialSpawnDuration); // If we have a spline emitter, set RGB channels // to a point sampled on the spline if (emitterType == EmitterType.Spline) { var p = spline.GetPoint(i / 1024.0f); splinePixels[i] = new Color(p.x, p.y, p.z); } curvePixels[i] = new Color(r, g, b, 1); } // Set pixels and reupload to the GPU splineSamplesTexture.SetPixels(splinePixels); splineSamplesTexture.Apply(); curveSamplesTexture.SetPixels(curvePixels); curveSamplesTexture.Apply(); }
public void init(float speed, float hoverHeight, float hoverVariance, float hoverSpeed, float rotationSpeed, float startPoint, float startdistance, float endDistance, BezierSpline spline, Transform boy) { this.speed = speed; this.hoverHeight = hoverHeight; this.hoverVariance = hoverVariance; this.hoverSpeed = hoverSpeed; this.rotationSpeed = rotationSpeed; this.spline = spline; this.boy = boy; this.endDistance = endDistance; randValue = Random.Range(0.1f, 0.9f); randDir = (int)Random.Range(0f, 2f); randDir = (randDir == 0) ? -1 : randDir; splineLength = spline.GetSplineLength(); transform.Rotate(0, Random.Range(0, 180), 0); t = startdistance / splineLength + startPoint; t = (t > 1f) ? 1f : t; transform.position = spline.GetPoint(t); }
private void Awake() { transform.position = _spline.GetPoint(0); }
private void GenMesh() { Mesh mesh = new Mesh(); mesh.name = "SPLINE MESH"; meshFilter.mesh = mesh; List <Vector3> verts = new List <Vector3>(); List <int> trianges = new List <int>(); List <Vector2> uvs = new List <Vector2>(); float increment = 1 / complexity; if (increment <= 0) { increment = 1.0f; } Vector3 start; Vector3 end; Vector3 vecWidth; Vector3 offset; Vector3 lastDir; Vector3 next; Vector3 curr; //Vector3 mid; Vector3 dir; //Vector3 pos; start = spline.GetPoint(0); next = spline.GetPoint(increment); end = spline.GetPoint(1); dir = spline.GetDirection(0); //print(dir); vecWidth = new Vector3(0, 0, width); lastDir = (next - start).normalized; curr = start; //mid = (start + end) / 2; //pos = transform.position; //start //verts.Add(start + vecWidth); //verts.Add(start + -vecWidth); //uvs.Add(new Vector2(0, 0)); //uvs.Add(new Vector2(1, 0)); for (float i = 0; i < 1; i += increment) { bool createVert = false; if (createVertsEveryStep) { createVert = true; } else { createVert = (Vector3.Dot(spline.GetDirection(i), lastDir) < directionChange || i == 0); } if (createVert) { lastDir = (next - curr).normalized; //print(i); offset = -Vector3.Cross(new Vector3(0, 1, 0), spline.GetDirection(i)).normalized *width; offset = new Vector3(offset.x, offset.y, Mathf.Abs(offset.z)); //print(offset); uvs.Add(new Vector2(0, i)); uvs.Add(new Vector2(1, i)); verts.Add(curr + offset); verts.Add(curr + -offset); } curr = next; next = spline.GetPoint(i + increment); } //for (float i = 0.1f; i <= 1; i += 0.1f) { // if(verts.Count % 4 == 0) { // int num = verts.Count; // trianges.Add(num - 3); // trianges.Add(num - 1); // trianges.Add(num - 2); // trianges.Add(num - 1); // trianges.Add(num - 0); // trianges.Add(num - 2); // } // uvs.Add(new Vector2(i, 0)); // uvs.Add(new Vector2(0, i)); // end = spline.GetPoint(i); // verts.Add(end + vecWidth); // verts.Add(end + -vecWidth); //} //end offset = -Vector3.Cross(new Vector3(0, 1, 0), spline.GetDirection(1)).normalized *width; verts.Add(end + offset); verts.Add(end + -offset); uvs.Add(new Vector2(0, 1)); uvs.Add(new Vector2(1, 1)); for (int i = 0; i <= verts.Count - 4; i += 2) { trianges.Add(i + 0); trianges.Add(i + 2); trianges.Add(i + 1); trianges.Add(i + 2); trianges.Add(i + 3); trianges.Add(i + 1); } //print(verts.Count); //print(trianges.Count); //print(uvs.Count); mesh.vertices = verts.ToArray(); mesh.triangles = trianges.ToArray(); mesh.uv = uvs.ToArray(); mesh.RecalculateNormals(); }
private IEnumerator Generate() { GetComponent <MeshFilter>().mesh = mesh = new Mesh(); mesh.name = "Procedural Grid"; rings.Clear(); while (transform.childCount > 0) { GameObject.DestroyImmediate(transform.GetChild(transform.childCount - 1)); } Vector3 LastDirection = spline.GetVelocity(0).normalized; float t = 0; while (t < 1) { t += jumps; if (MaxAngle < Vector3.Angle(LastDirection, spline.GetVelocity(t).normalized)) { //rings.Add(Vector3.Angle(LastDirection, spline.GetVelocity(t).normalized)); rings.Add(t); LastDirection = spline.GetVelocity(t).normalized; } // } float x, y, angle = 0; vertices = new Vector3[circleVertices * (rings.Count + 1)]; yield return(null); Vector2[] uv = new Vector2[vertices.Length]; for (int j = 0; j < rings.Count + 1; j++) { int start = j * circleVertices; Transform tr = new GameObject("CurvePoint").transform; Vector3 direction = spline.GetVelocity(rings[j]).normalized; tr.rotation = Quaternion.LookRotation(direction); Vector3 point = spline.GetPoint(t) - transform.position; tr.parent = transform; tr.position = point; for (int i = start; i < start + circleVertices; i++) { x = radius * Mathf.Cos(angle * Mathf.Deg2Rad); y = radius * Mathf.Sin(angle * Mathf.Deg2Rad); //print(point); vertices[i] = tr.TransformPoint(new Vector3(x, y, 0)); uv[i] = new Vector2((float)i / circleVertices, 0); angle += 360 / circleVertices; //yield return new WaitForSecondsRealtime(0.01f); } } /* * mesh.vertices = vertices; * int[] triangles = new int[(circleVertices) * (rings.Count + 1) * 6]; * int vert = 0, vertRef = 0, circle = 0, total = 0; * for(int r = 0; r < rings.Count; r++){ * circle = r * circleVertices; * string result; * for(vertRef = 0; vertRef < circleVertices - 1; vertRef++){ * vert = (vertRef * 6) + (circleVertices * 6) * r; * result = "["; * result += triangles[(0 + vert)] = vertRef + circle; * result += triangles[(1 + vert)] = vertRef + 1 + circle; * result += triangles[(2 + vert)] = circleVertices + vertRef + circle; * result += "]["; * result += triangles[(3 + vert)] = vertRef + 1 + circle; * result += triangles[(5 + vert)] = circleVertices + vertRef + circle; * result += triangles[(4 + vert)] = vertRef + circleVertices + 1 + circle; * //print(result + "]"); * } * vert = (vertRef * 6) + (circleVertices * 6) * r; * result = "["; * result += triangles[(2 + vert)] = vertRef + circle; * result += triangles[(1 + vert)] = vertRef + 1 + circle; * result += triangles[(0 + vert)] = circle; * result += "]["; * result += triangles[(4 + vert)] = vertRef + 1 + circle; * result += triangles[(5 + vert)] = circleVertices + vertRef + circle; * result += triangles[(3 + vert)] = vertRef + circle; * //print(result + "]"); * } * mesh.triangles = triangles; * * mesh.RecalculateNormals(); * * mesh.uv = uv; */ }
//Function called from Update to get the position where the player ship will be private Vector3 LeadShipPosition() { //The vec3 position that we return Vector3 targetPos = this.targetPlayer.transform.position; //Float that holds the position between our muzzle and the player ship float distToTarget = Vector3.Distance(this.ourWeapon.muzzleAudio.transform.position, targetPos); //Finding the amount of time it would take for our weapon's projectile would take to cover that distance //Using the formula Velocity = Distance / Time ===> Time = Distance / Velocity float projectileTime = distToTarget / this.ourWeapon.firedProjectile.forwardVelocity; //Now that we know about how long it will take for the projectile to reach the player's CURRENT position, //We need to guess how far along they will be using their current velocity //If the ship is in a free movement zone, we use their forward velocity if (this.targetPlayer.ourFreeMovement.enabled) { //Getting the direction and magnitude that the velocity is facing Vector3 velocityOffset = this.targetPlayer.ourRailMovement.railParentObj.ourRigidbody.velocity; //Multiplying the velocity velocityOffset = velocityOffset * projectileTime; //Adding the forward velocity offset to the target position targetPos += velocityOffset; } //If the ship is in a rail movement zone, we need to use the rail position else if (this.targetPlayer.ourRailMovement.enabled && this.targetPlayer.ourRailMovement.railParentObj.ourSplineMoveRB.splineToFollow != null) { //Getting the reference to the spline that the target ship is moving on BezierSpline shipSpline = this.targetPlayer.ourRailMovement.railParentObj.ourSplineMoveRB.splineToFollow; //Getting the current amount of time that the ship has already traveled float currentSplineTime = this.targetPlayer.ourRailMovement.railParentObj.ourSplineMoveRB.CurrentSplineTime; //Getting the total time that the player will have to travel along the spline float totalSplineTime = this.targetPlayer.ourRailMovement.railParentObj.ourSplineMoveRB.timeToComplete; //Getting the speed multiplier that the player is moving at float speedMultiplier = this.targetPlayer.ourRailMovement.railParentObj.ourSplineMoveRB.speedMultiplier; //Getting the adjusted percent along the spline that the player is currently at float adjustedCurrentPercent = currentSplineTime / totalSplineTime; adjustedCurrentPercent = shipSpline.GetAdjustedPercentFromTime(adjustedCurrentPercent); //Getting the adjusted percent along the spline that the player is going to be at float adjustedTargetPercent = projectileTime * (speedMultiplier); adjustedTargetPercent += currentSplineTime; adjustedTargetPercent = adjustedTargetPercent / totalSplineTime; adjustedTargetPercent = shipSpline.GetAdjustedPercentFromTime(adjustedTargetPercent); //Getting the position along the spline that the ship will be at when taking into account the projectile time targetPos = shipSpline.GetPoint(adjustedTargetPercent); //Finding the offset that the player ship is from the rail center Vector3 currentOffset = this.targetPlayer.transform.InverseTransformPoint(shipSpline.GetPoint(adjustedCurrentPercent)); currentOffset = new Vector3(-currentOffset.x, -currentOffset.y, -currentOffset.z); //Adding the offset that the player ship is from the target position targetPos += shipSpline.GetQuaternionAtPercent(adjustedTargetPercent) * currentOffset; } //Returning our target pos return(targetPos); }
void DrawBezierPatch(BezierSpline patch,int segs) { Vector3 lastPoint = patch.point0; //Handles.DrawWireSphere(patch.point0,0.003f*Vector3.Distance(Camera.current.transform.position,patch.point0)); //Handles.DrawWireSphere(patch.point1,0.003f*Vector3.Distance(Camera.current.transform.position,patch.point1)); if (!patch.linear) { Handles.color = Color.red; Handles.DrawLine(patch.point0,patch.tangetPos0); Handles.DrawLine(patch.point1,patch.tangetPos1); } bool colorSwap = false; for (int i = 0; i < segs+1; i++) { float t = (float)i/(float)segs; Vector3 p = patch.GetPoint(t); if (colorSwap) { Handles.color = new Color(1.0f,1.0f,1.0f,1.0f); } else { Handles.color = new Color(0.2f,0.2f,0.2f,1.0f); } Handles.DrawLine(lastPoint,p); lastPoint = p; colorSwap = !colorSwap; } Handles.color = Color.white; }
private void OnSceneGUI() { spline = target as BezierSpline; handleTransform = spline.transform; handleRotation = handleTransform.rotation; Vector3 p0 = ShowPoint (0); for (int i = 1; i < spline.ControlPointCount; i += 3) { Vector3 p1 = ShowPoint (i); Vector3 p2 = ShowPoint (i+1); Vector3 p3 = ShowPoint (i+2); Handles.color = Color.gray; Handles.DrawLine (p0, p1); Handles.DrawLine (p2, p3); //Handles.DrawBezier (p0, p3, p1, p2, Color.white, null, 2f); p0 = p3; } Handles.color = Color.white; Vector3 lineStart = spline.GetPoint (0f); for (int i = 1; i <= lineSteps; i++) { Vector3 lineEnd = spline.GetPoint((float) i/lineSteps); Handles.DrawLine(lineStart, lineEnd); lineStart = lineEnd; } }
void TakeStep() { if (!FootInPos) { if (firstFrame) { //transform.LookAt(new Vector3(Spline.GetPoint(stepPositionInSpline[0]).x, transform.position.y, Spline.GetPoint(stepPositionInSpline[0]).z)); stepTracjectory.points[0] = targets[currentStep].position; stepTracjectory.points[1] = targets[currentStep].position + new Vector3(0 + Random.Range(-NoiseX, NoiseX), 1 + Random.Range(-NoiseY, NoiseY), 0 + Random.Range(-NoiseZ, NoiseZ)); stepTracjectory.points[2] = Steps[0] + new Vector3(0 + Random.Range(-NoiseX, NoiseX), 1 + Random.Range(-NoiseY, NoiseY), 0 + Random.Range(-NoiseZ, NoiseZ)); stepTracjectory.points[3] = Steps[0]; firstFrame = false; } //Debug.Log(stepProgress); stepProgress += Time.deltaTime * legSpeed; //rFootTarget.transform.RotateAround(tempFootPos, new Vector3(-1,1,0), 40 *Time.deltaTime); //rFootTarget.transform.position = tempFootPos + new Vector3(0, Mathf.Sin(stepProgress) * (currentStepLength), Mathf.Cos(stepProgress) * (currentStepLength)); //rFootTarget.position = tempFootPos; //rFootTarget.Translate(new Vector3(0, Mathf.Sin(stepProgress) * (currentStepLength/2), Mathf.Cos(stepProgress) * (currentStepLength / 2))); targets[currentStep].position = stepTracjectory.GetPoint(stepProgress); //if ((targets[currentStep].position - Steps[0]).magnitude < 0.05f) if (targets[currentStep].position == stepTracjectory.GetPoint(1)) { //Debug.Log("Step Taken"); firstFrame = true; stepProgress = 0; FootInPos = true; } } else if (!bodyInPos) { bodyProgress += Time.deltaTime / 100; //transform.LookAt(new Vector3(Spline.GetPoint(bodyProgress + 0.01f).x,transform.position.y, Spline.GetPoint(bodyProgress+0.01f).z)); transform.LookAt(new Vector3(Spline.GetPoint(stepPositionInSpline[0]).x, transform.position.y, Spline.GetPoint(stepPositionInSpline[0]).z)); //transform.position = new Vector3(Spline.GetPoint(bodyProgress).x, transform.position.y, Spline.GetPoint(bodyProgress).z); transform.Translate(Vector3.forward * Time.deltaTime); //if (prevDistance<number && prevDistance != 0) if (Vector3.Distance(transform.position, new Vector3(Spline.GetPoint(stepPositionInSpline[0]).x, transform.position.y, Spline.GetPoint(stepPositionInSpline[0]).z)) < 0.1) { // Debug.Log("BOdy moved"); bodyInPos = true; } } else { stepPositionInSpline.RemoveAt(0); leftStepTaken = true; FootInPos = false; bodyInPos = false; Steps.RemoveAt(0); currentStep = (currentStep + 1) % legs.Count; } }
private void OnSceneGUI() { spline = target as BezierSpline; handleTransform = spline.transform; handleRotation = Tools.pivotRotation == PivotRotation.Local ? handleTransform.rotation : Quaternion.identity; Vector3 p0 = ShowPoint(0); for (int i = 1; i < spline.GetControlPointCount(); i += 3) { Vector3 p1 = ShowPoint(i); Vector3 p2 = ShowPoint(i + 1); Vector3 p3 = ShowPoint(i + 2); Handles.color = Color.gray; Handles.DrawLine(p0, p1); Handles.DrawLine(p2, p3); Handles.color = Color.white; Vector3 lineStart = spline.GetPoint(i); for (int step = 0; step <= spline.GetSmoothness(); step++) { Vector3 lineEnd = spline.GetPoint(step / (float)spline.GetSmoothness()); Handles.DrawLine(lineStart, lineEnd); lineStart = lineEnd; } //Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 5f); p0 = p3; } //ShowDirections(); }
void Update() { cachedTransform.position = Vector3.Lerp(cachedTransform.position, spline.GetPoint(progress), movementLerpModifier * Time.deltaTime); if (lookForward) { Quaternion targetRotation; if (isGoingForward) { targetRotation = Quaternion.LookRotation(spline.GetTangent(progress)); } else { targetRotation = Quaternion.LookRotation(-spline.GetTangent(progress)); } cachedTransform.rotation = Quaternion.Lerp(cachedTransform.rotation, targetRotation, rotationLerpModifier * Time.deltaTime); } if (isGoingForward) { progress += Time.deltaTime / travelTime; if (progress > 1f) { if (!onPathCompletedCalledAt1) { onPathCompleted.Invoke(); onPathCompletedCalledAt1 = true; } if (travelMode == TravelMode.Once) { progress = 1f; } else if (travelMode == TravelMode.Loop) { progress -= 1f; } else { progress = 2f - progress; isGoingForward = false; } } else { onPathCompletedCalledAt1 = false; } } else { progress -= Time.deltaTime / travelTime; if (progress < 0f) { if (!onPathCompletedCalledAt0) { onPathCompleted.Invoke(); onPathCompletedCalledAt0 = true; } if (travelMode == TravelMode.Once) { progress = 0f; } else if (travelMode == TravelMode.Loop) { progress += 1f; } else { progress = -progress; isGoingForward = true; } } else { onPathCompletedCalledAt0 = false; } } }
public void GeneratePointsOnBezier() { if (pathPoints == null) { return; } if (spline == null) { return; } DeleteAllPoints(); float progress = 0; for (int i = 0; i < splinePoinsAmount; i++) { if (i > 0) { progress = 1f / splinePoinsAmount * (i); } PathPoint newPoint = new PathPoint(); newPoint.position = spline.GetPoint(progress); newPoint.rotation = Quaternion.LookRotation(spline.GetDirection(progress)); newPoint.gravity = gravity; // Create PathPoing Collider GameObject go = new GameObject("Path collider " + i); go.transform.parent = gameObject.transform; go.transform.position = newPoint.position; go.transform.rotation = newPoint.rotation; BoxCollider colliderNormal = go.AddComponent <BoxCollider>(); colliderNormal.size = new Vector3(10f, 10f, 0.05f); colliderNormal.isTrigger = true; PathNodeCollider pn = go.AddComponent <PathNodeCollider>(); pn.indexGravityNode = i; // Create Reverse collider GameObject goReverse = new GameObject("Reverse Path collider " + i); goReverse.transform.parent = gameObject.transform; goReverse.transform.position = spline.GetPoint(progress + 0.001f); goReverse.transform.rotation = newPoint.rotation; BoxCollider colliderReverse = goReverse.AddComponent <BoxCollider>(); colliderReverse.size = new Vector3(10f, 10f, 0.05f); colliderReverse.isTrigger = true; PathNodeReverseCollider pnReverse = goReverse.AddComponent <PathNodeReverseCollider>(); pn.reverseCollider = pnReverse; pnReverse.normalCollider = pn; newPoint.collider = colliderNormal; newPoint.colliderReverse = colliderReverse; pathPoints.pointsList.Add(newPoint); } if (pathPoints.pointsList.Count > 0) { activeIndex = 0; } UpdateActivePoint(); }
private void OnSceneGUI() { spline = target as BezierSpline; handleTransform = spline.transform; handleRotation = Tools.pivotRotation == PivotRotation.Local ? handleTransform.rotation : Quaternion.identity; Vector3 p0 = ShowPoint(0); for (int i = 1; i < spline.ControlPointCount; i += 3) { Vector3 p1 = ShowPoint(1); Vector3 p2 = ShowPoint(2); Vector3 p3 = ShowPoint(3); Handles.color = Color.gray; Handles.DrawLine(p0, p1); Handles.DrawLine(p2, p3); Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 2f); p0 = p3; } ShowDirections(); Handles.color = Color.white; Vector3 lineStart = spline.GetPoint(0f); Handles.color = Color.green; Handles.DrawLine(lineStart, lineStart + spline.GetDirection(0f)); for (int i = 1; i <= lineSteps; i++) { Vector3 lineEnd = spline.GetPoint(i / (float)lineSteps); Handles.color = Color.white; Handles.DrawLine(lineStart, lineEnd); Handles.color = Color.green; Handles.DrawLine(lineEnd, lineEnd + spline.GetDirection(i / (float)lineSteps)); lineStart = lineEnd; } }
public virtual void Update() { if (fixedDuration) { if (goingForeward) { progress += Time.deltaTime / (duration); if (progress > 1f) { if (mode == SplineWalkerMode.Once) { progress = 1f; } else if (mode == SplineWalkerMode.Loop) { progress -= 1f; } else if (mode == SplineWalkerMode.Destroy) { Destroy(gameObject); } else { progress = 2f - progress; goingForeward = false; } } } else { progress -= Time.deltaTime / (duration); if (progress <= 0f) { progress = -progress; goingForeward = true; } } } else { if (goingForeward) { if (progress >= 1f) { if (mode == SplineWalkerMode.Once) { progress = 1f; } else if (mode == SplineWalkerMode.Loop) { progress -= 1f; } else if (mode == SplineWalkerMode.Destroy) { Destroy(gameObject); } else { progress = 1f; goingForeward = false; } } else { float pathOnePercent = Vector3.Distance(spline.GetPoint(progress), spline.GetPoint(progress + 0.1f)); float realOnePercent = spline.splineLength * 0.1f; float Distortion = realOnePercent / pathOnePercent; float realPercentToMove = (velocity * Time.deltaTime) / spline.splineLength; progress = (realPercentToMove * Distortion) + progress; } } else { if (progress <= 0f) { progress = 0; goingForeward = true; } else { float pathOnePercent = Vector3.Distance(spline.GetPoint(progress), spline.GetPoint(progress - 0.1f)); float realOnePercent = spline.splineLength * 0.1f; float Distortion = realOnePercent / pathOnePercent; float realPercentToMove = (-velocity * Time.deltaTime) / spline.splineLength; progress = (realPercentToMove * Distortion) + progress; } } } Vector3 position = spline.GetPoint(progress); transform.localPosition = position; if (lookForward) { transform.LookAt(position + spline.GetDirection(progress)); } }
void OnWizardCreate() { GameObject newTrackMesh = new GameObject("TrackMesh"); string meshName = newTrackMesh.name + spline.name; string meshPrefabPath = "Assets/Editor/" + meshName + ".asset"; Mesh mesh = (Mesh)AssetDatabase.LoadAssetAtPath(meshPrefabPath, typeof(Mesh)); if (mesh == null) { mesh = new Mesh(); mesh.name = meshName; int run = 0; int n = spline.CurveCount * (int)sectionsPerCurve; Vector3[] points = new Vector3[n + 1]; run = 0; for (float t = 0.0f; t <= 1.0f; t += 1.0f / (float)n) { points[run++] = spline.GetPoint(t); } Vector3[] vertices = new Vector3[18 + (n - 1) * 2]; Vector2[] uvs = new Vector2[vertices.Length]; float w = 0; float h = 0; float u = 0; run = 0; for (int s = 0; s < 2; s++) { switch (s) { case 0: w = -trackWidth / 2f; h = trackHeight / 2f; u = 0.0f; break; case 1: w = trackWidth / 2f; h = trackHeight / 2f; u = 1.0f; break; default: break; } Vector3 fwd = Vector3.forward, left = Vector3.left; for (int i = 0; i <= n; i++) { if (i != n) { fwd = points[i + 1] - points[i]; fwd.y = 0; fwd.Normalize(); left = Vector3.Cross(Vector3.up, fwd); } vertices[run] = points[i] + left * w + Vector3.up * h; if ((i % 2) == 1) { uvs[run].Set(u, 1.0f); } else { uvs[run].Set(u, 0.0f); } run++; } } int[] triangles = new int[n * 2 * 3]; run = 0; for (int s = 0; s < 1; s++) { for (int i = 0; i < n; i++) { triangles[run + 0] = s * (n + 1) + i; triangles[run + 1] = s * (n + 1) + i + 1; triangles[run + 2] = ((s + 1) % 8) * (n + 1) + i; triangles[run + 3] = s * (n + 1) + i + 1; triangles[run + 4] = ((s + 1) % 8) * (n + 1) + i + 1; triangles[run + 5] = ((s + 1) % 8) * (n + 1) + i; run += 6; } } mesh.vertices = vertices; mesh.uv = uvs; mesh.triangles = triangles; mesh.RecalculateNormals(); AssetDatabase.CreateAsset(mesh, meshPrefabPath); AssetDatabase.SaveAssets(); } MeshFilter mf = newTrackMesh.AddComponent <MeshFilter>(); mf.mesh = mesh; newTrackMesh.AddComponent <MeshRenderer>(); if (addCollider) { MeshCollider mc = newTrackMesh.AddComponent <MeshCollider>(); mc.sharedMesh = mf.sharedMesh; } Selection.activeObject = newTrackMesh; }
private void Update() { if (!move) { return; } if (goingForward) { progress += Time.deltaTime / duration; if (progress > 1f) { if (mode == SplineWalkerMode.Once) { progress = 1f; } else if (mode == SplineWalkerMode.Loop) { progress -= 1f; } else { progress = 2f - progress; goingForward = false; } } } else { progress -= Time.deltaTime / duration; if (progress < 0f) { progress = -progress; goingForward = true; } } float easedProgress = progress; switch (easing) { case EaseType.SmoothStep: easedProgress = Ease.SmoothStep(progress); break; case EaseType.SmootherStep: easedProgress = Ease.SmootherStep(progress); break; case EaseType.EaseIn: easedProgress = Ease.EaseIn(progress); break; case EaseType.EaseOut: easedProgress = Ease.EaseOut(progress); break; case EaseType.ExpOut: easedProgress = Ease.ExpOut(progress); break; } Vector3 position = spline.GetPoint(progress); transform.position = position; if (lookForward) { transform.LookAt(position + spline.GetDirection(progress)); } }
private IEnumerator Generate() { GetComponent <MeshFilter>().mesh = mesh = new Mesh(); mesh.name = "Procedural Grid"; float x, y, z = 0, angle = 0, t = 0; vertices = new Vector3[circleVertices * (rings + 1)]; Vector2[] uv = new Vector2[vertices.Length]; for (int j = 0; j < rings + 1; j++) { int start = j * circleVertices; t = (float)(j) / (float)rings; Transform tr = new GameObject("CurvePoint").transform; Vector3 direction = spline.GetVelocity(t).normalized; tr.rotation = Quaternion.LookRotation(direction); print(direction); Vector3 point = spline.GetPoint(t) - transform.position; tr.parent = transform; tr.position = point; for (int i = start; i < start + circleVertices; i++) { x = radius * Mathf.Cos(angle * Mathf.Deg2Rad); y = radius * Mathf.Sin(angle * Mathf.Deg2Rad); //print(point); vertices[i] = tr.TransformPoint(new Vector3(x, y, 0)); uv[i] = new Vector2((float)i / circleVertices, 0); angle += 360 / circleVertices; yield return(new WaitForSecondsRealtime(0.01f)); } } mesh.vertices = vertices; int[] triangles = new int[(circleVertices) * (rings + 1) * 6]; int vert = 0, vertRef = 0, circle = 0, total = 0; for (int r = 0; r < rings; r++) { circle = r * circleVertices; string result; for (vertRef = 0; vertRef < circleVertices - 1; vertRef++) { vert = (vertRef * 6) + (circleVertices * 6) * r; result = "["; result += triangles[(0 + vert)] = vertRef + circle; result += triangles[(1 + vert)] = vertRef + 1 + circle; result += triangles[(2 + vert)] = circleVertices + vertRef + circle; result += "]["; result += triangles[(3 + vert)] = vertRef + 1 + circle; result += triangles[(5 + vert)] = circleVertices + vertRef + circle; result += triangles[(4 + vert)] = vertRef + circleVertices + 1 + circle; //print(result + "]"); } vert = (vertRef * 6) + (circleVertices * 6) * r; result = "["; result += triangles[(2 + vert)] = vertRef + circle; result += triangles[(1 + vert)] = vertRef + 1 + circle; result += triangles[(0 + vert)] = circle; result += "]["; result += triangles[(4 + vert)] = vertRef + 1 + circle; result += triangles[(5 + vert)] = circleVertices + vertRef + circle; result += triangles[(3 + vert)] = vertRef + circle; //print(result + "]"); } mesh.triangles = triangles; mesh.RecalculateNormals(); mesh.uv = uv; }
// Use this for initialization void Start() { transform.position = new Vector3(0, 5, 0); legOffsets = new float[legs.Count]; for (int i = 0; i < legOffsets.Length; i++) { legOffsets[i] = legs[i % legs.Count].transform.position.x - transform.position.x; } targets = new Transform[legs.Count]; RaycastHit hit; int layerMask = 1 << 8; transform.position = new Vector3(Spline.gameObject.transform.position.x + Spline.points[0].x, transform.position.y, Spline.gameObject.transform.position.z + Spline.points[0].z); transform.LookAt(new Vector3(Spline.GetPoint(0.01f).x, transform.position.y, Spline.GetPoint(0.01f).z)); if (Physics.Raycast(transform.position, Vector3.down, out hit, 100, layerMask)) { Vector3 pos = hit.transform.position; pos.y += legs[0].GetLegLength() * Uprightness; pos.z = transform.position.z; pos.x = transform.position.x; transform.position = pos; } for (int i = 0; i < targets.Length; i++) { targets[i] = new GameObject().transform; legs[i].target = targets[i]; targets[i].position = legs[i].transform.position; targets[i].position = new Vector3(targets[i].position.x, targets[i].position.y - (legs[i].GetLegLength() * Uprightness), targets[i].position.z); } //LeftFoot step positions float CheckedDis = 0; Vector3 lastStepPos = targets[0].position; //the big step meister bool done = false; int denstoretælleleg = 0; while (!done) { GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere); sphere.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f); //Debug.Log(i % 2); sphere.transform.position = Spline.GetPoint(0); sphere.transform.LookAt(Spline.GetPoint(0) + Spline.GetDirection(0)); sphere.transform.Translate(legOffsets[denstoretælleleg % legs.Count], 0, 0); while (true) { CheckedDis += 0.005f; sphere.transform.position = Spline.GetPoint(CheckedDis); sphere.transform.LookAt(Spline.GetPoint(CheckedDis) + Spline.GetDirection(CheckedDis)); sphere.transform.Translate(legOffsets[denstoretælleleg % legs.Count], 0, 0); if (Vector3.Distance(lastStepPos, sphere.transform.position) >= stepLength) { break; } if (CheckedDis > 1) { done = true; break; } } stepPositionInSpline.Add(CheckedDis); Steps.Add(sphere.transform.position); lastStepPos = sphere.transform.position; denstoretælleleg++; Destroy(sphere); } CheckedDis = 0; }
// Use this for initialization void Start() { t = 0; currentSpline = startingSpline; transform.position = currentSpline.GetPoint(t); transform.rotation = currentSpline.GetOrientation(t, Vector3.Lerp(currentSpline.startNode.transform.up, currentSpline.endNode.transform.up, t)); lastForward = transform.forward; //currentSpline.GetComponent<MeshCollider>().enabled = true; }
void ReallocateNodeOverSpline(Transform node, BezierSpline spline, int depth) { float newPosition; // Collide with spline that can belong to 2 possible objects, biffurcation or curve Curve curve = spline.transform.parent.GetComponent <Curve>(); Bifurcation bifurcation = spline.transform.parent.GetComponent <Bifurcation>(); if (curve != null) {// we are in a curve Debug.DrawLine(transform.position, nodeToFollow.position, Color.cyan); } if (bifurcation != null) {// we are in a bifurcation if (bifurcation.splines[0].isPath) { spline = bifurcation.splines[0]; } else { spline = bifurcation.splines[1]; } } newPosition = spline.GetClosestPoint(transform.position + transform.forward * distToNode, 0.01f); nodeToFollow.position = spline.GetPoint(newPosition); nodeToFollow.rotation = spline.GetOrientation(newPosition, transform.up); // end or beggining of spline reached, check next/previous spline if (newPosition == 2) { // jump to previous spline if (depth == 1) { // avoid infinite recursive loops nodeToFollow.position = spline.startNode.transform.position; nodeToFollow.rotation = spline.startNode.transform.rotation; return; } RaycastHit hit; Vector3 dir = -spline.startNode.transform.forward; //if (spline.startNode.reverse == true) dir *= -1; if (Physics.Raycast(spline.startNode.position + dir + new Vector3(0, 2, 0), -transform.up, out hit, 30)) { spline = hit.collider.transform.GetComponent <BezierSpline>(); } ReallocateNodeOverSpline(nodeToFollow, spline, 1); } if (newPosition == 3) { // jump to next spline if (depth == 1) { // avoid infinite recursive loops nodeToFollow.position = spline.endNode.transform.position; nodeToFollow.rotation = spline.endNode.transform.rotation; return; } RaycastHit hit; Vector3 dir = spline.endNode.transform.forward; //if (spline.endNode.reverse == true) // dir *= -1; if (Physics.Raycast(spline.endNode.position + dir + new Vector3(0, 2, 0), -transform.up, out hit, 30)) { spline = hit.collider.transform.GetComponent <BezierSpline>(); } ReallocateNodeOverSpline(nodeToFollow, spline, 1); } }
private void Update() { if (move) { if (goingForward) { progress += Time.deltaTime / duration; if (progress > 1f) { if (mode == SplineWalkerMode.Once) { progress = 1f; if (onFinish != null) { onFinish.Invoke(); } } else if (mode == SplineWalkerMode.Loop) { progress -= 1f; } else { progress = 2f - progress; goingForward = false; } } } else { progress -= Time.deltaTime / duration; if (progress < 0f) { if (mode == SplineWalkerMode.Once) { progress = 0f; } else if (mode == SplineWalkerMode.Loop) { progress += 1f; } else { progress = -progress; goingForward = true; } } } Vector3 position = spline.GetPoint(progress); if (needFixHeight) { position += GameModel.Instance.heightOffset; } transform.position = position; // transform.localPosition = position; if (lookForward) { transform.LookAt(position + spline.GetDirection(progress)); transform.Rotate(rotationAdjustment); } } }
void ReallocateNodeOverSpline(Transform node, BezierSpline spline, int depth) { float newPosition; // Collide with spline that can belong to 2 possible objects, biffurcation or curve Curve curve = spline.transform.parent.GetComponent<Curve>(); Bifurcation bifurcation = spline.transform.parent.GetComponent<Bifurcation>(); if (curve != null) {// we are in a curve Debug.DrawLine(transform.position, nodeToFollow.position, Color.cyan); } if (bifurcation != null) {// we are in a bifurcation if (bifurcation.splines[0].isPath) spline = bifurcation.splines[0]; else spline = bifurcation.splines[1]; } newPosition = spline.GetClosestPoint(transform.position + transform.forward * distToNode, 0.01f); nodeToFollow.position = spline.GetPoint(newPosition); nodeToFollow.rotation = spline.GetOrientation(newPosition, transform.up); // end or beggining of spline reached, check next/previous spline if (newPosition == 2) {// jump to previous spline if (depth == 1) {// avoid infinite recursive loops nodeToFollow.position = spline.startNode.transform.position; nodeToFollow.rotation = spline.startNode.transform.rotation; return; } RaycastHit hit; Vector3 dir = -spline.startNode.transform.forward; //if (spline.startNode.reverse == true) dir *= -1; if (Physics.Raycast(spline.startNode.position + dir + new Vector3(0, 2, 0), -transform.up, out hit, 30)) { spline = hit.collider.transform.GetComponent<BezierSpline>(); } ReallocateNodeOverSpline(nodeToFollow, spline, 1); } if (newPosition == 3) {// jump to next spline if (depth == 1) {// avoid infinite recursive loops nodeToFollow.position = spline.endNode.transform.position; nodeToFollow.rotation = spline.endNode.transform.rotation; return; } RaycastHit hit; Vector3 dir = spline.endNode.transform.forward; //if (spline.endNode.reverse == true) // dir *= -1; if (Physics.Raycast(spline.endNode.position + dir + new Vector3(0, 2, 0), -transform.up, out hit, 30)) { spline = hit.collider.transform.GetComponent<BezierSpline>(); } ReallocateNodeOverSpline(nodeToFollow, spline, 1); } }
public void BuildRollercoasterTrack(GameObject trackGameObject, GameObject splineRootGameObject, GameObject leftRailPrefab, GameObject rightRailPrefab, GameObject crossBeamPrefab, float resolution) { BezierSpline bezierSpline = splineRootGameObject.GetComponent <BezierSpline>(); // Delete all of the children of the track holding game object List <Component> childComponents = new List <Component>(trackGameObject.GetComponentsInChildren(typeof(Transform))); //Returns all components of Type type in the GameObject and any of its children. List <Transform> childTransforms = childComponents.ConvertAll(c => (Transform)c); childTransforms.Remove(trackGameObject.transform); //Remove the current game object (parent)'s transform from the list. We need only the transforms of the children foreach (Transform childTransform in childTransforms) { if (childTransform.gameObject.name == "left rail" || childTransform.gameObject.name == "right rail") { UnityEngine.Object.DestroyImmediate(childTransform.gameObject.GetComponent <MeshFilter>().sharedMesh); } UnityEngine.Object.DestroyImmediate(childTransform.gameObject); //Destroy cannot be called in edit mode } // Build a list of affine transformation matricies that represent the track sections List <Matrix4x4> leftTrackPolyline = new List <Matrix4x4>(); List <Matrix4x4> rightTrackPolyline = new List <Matrix4x4>(); //GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube); //cube.transform.parent = transform; //cube.transform.localScale = new Vector3(0.4f, 0.4f, 0.4f); //cube.transform.position = bezierSpline.GetPoint(0); //cube.transform.localRotation = Quaternion.LookRotation(bezierSpline.GetTangent(0)); //GameObject cube2 = GameObject.CreatePrimitive(PrimitiveType.Cube); //cube2.transform.parent = transform; //cube2.transform.localScale = new Vector3(0.4f, 0.4f, 0.4f); //cube2.transform.position = bezierSpline.GetPoint(1); //cube2.transform.localRotation = Quaternion.LookRotation(bezierSpline.GetTangent(1)); for (float t = 0; t <= 1; t += resolution) { //print("T: " + t); Transform trans = new GameObject().transform; trans.position = bezierSpline.GetPoint(t); trans.rotation = Quaternion.LookRotation(bezierSpline.GetTangent(t)); leftTrackPolyline.Add(trans.localToWorldMatrix * leftRailPrefab.transform.localToWorldMatrix); rightTrackPolyline.Add(trans.localToWorldMatrix * rightRailPrefab.transform.localToWorldMatrix); UnityEngine.Object.DestroyImmediate(trans.gameObject); //Debug.Log(trans.localToWorldMatrix); float t2 = t + resolution + resolution; if (bezierSpline.loop && t2 >= 1) { Transform trans1 = new GameObject().transform; trans1.position = bezierSpline.GetPoint(0); trans1.rotation = Quaternion.LookRotation(bezierSpline.GetTangent(0)); leftTrackPolyline.Add(trans1.localToWorldMatrix * leftRailPrefab.transform.localToWorldMatrix); rightTrackPolyline.Add(trans1.localToWorldMatrix * rightRailPrefab.transform.localToWorldMatrix); UnityEngine.Object.DestroyImmediate(trans1.gameObject); break; } } // Generate the rails GameObject leftRail = new GameObject(); Mesh leftMesh = new Mesh(); leftRail.name = "left rail"; leftRail.transform.parent = trackGameObject.transform; leftRail.AddComponent <MeshFilter>(); leftRail.GetComponent <MeshFilter>().sharedMesh = leftMesh; // Not allowed to access MeshFilter.mesh on prefab object. So Use MeshFilter.sharedMesh leftRail.AddComponent <MeshRenderer>(); leftRail.GetComponent <MeshRenderer>().sharedMaterial = leftRailPrefab.GetComponent <MeshRenderer>().sharedMaterial; // Not allowed to access MeshRenderer.material on prefab object. So Use MeshRenderer.sharedMaterial MeshExtrusion.ExtrudeMesh(leftRailPrefab.GetComponent <MeshFilter>().sharedMesh, leftRail.GetComponent <MeshFilter>().sharedMesh, leftTrackPolyline.ToArray(), false); GameObject rightRail = new GameObject(); Mesh rightMesh = new Mesh(); rightRail.name = "right rail"; rightRail.transform.parent = trackGameObject.transform; rightRail.AddComponent <MeshFilter>(); rightRail.GetComponent <MeshFilter>().sharedMesh = rightMesh; rightRail.AddComponent <MeshRenderer>(); rightRail.GetComponent <MeshRenderer>().sharedMaterial = rightRailPrefab.GetComponent <MeshRenderer>().sharedMaterial; MeshExtrusion.ExtrudeMesh(rightRailPrefab.GetComponent <MeshFilter>().sharedMesh, rightRail.GetComponent <MeshFilter>().sharedMesh, rightTrackPolyline.ToArray(), false); // generateCrossBeams if (crossBeamPrefab != null) { // Generate the cross bars float distSinceLastCrossbar = 0; float cbRes = resolution / 5.0f; float beamDistance = 2.0f; for (float t = 0; t <= 1; t += cbRes) { Vector3 dP = bezierSpline.GetPoint(t) - bezierSpline.GetPoint(t - cbRes); distSinceLastCrossbar += dP.magnitude; if (distSinceLastCrossbar >= beamDistance) { GameObject crossbar = UnityEngine.Object.Instantiate(crossBeamPrefab); //Creates a gameObject from the prefab crossbar.transform.parent = trackGameObject.transform; crossbar.transform.position = bezierSpline.GetPoint(t); crossbar.transform.rotation = Quaternion.LookRotation(bezierSpline.GetTangent(t)); crossbar.transform.position += crossbar.transform.right * crossBeamPrefab.transform.position.x; crossbar.transform.position += crossbar.transform.up * crossBeamPrefab.transform.position.y; crossbar.transform.position += crossbar.transform.forward * crossBeamPrefab.transform.position.z; crossbar.transform.rotation *= crossBeamPrefab.transform.rotation; distSinceLastCrossbar -= beamDistance; } } } }
void Update() { if (applicationExiting) { return; } if (cameraTexture == null || predictionTexture == null || carController == null) { return; } ogmaneo.Vec2i pixelPos = new Vec2i(); // Remember currently active render texture RenderTexture currentActiveRT = RenderTexture.active; // Transfer the camera capture into the prediction texture (temporarily) RenderTexture.active = cameraTexture; predictionTexture.ReadPixels(new Rect(0, 0, _inputWidth, _inputHeight), 0, 0); predictionTexture.Apply(); // Restore active render texture RenderTexture.active = currentActiveRT; // Transfer the RGB camera texture into ValueField2D fields Color actualPixel = new Color(); Color yuvPixel = new Color(0.0f, 0.0f, 0.0f); for (int x = 0; x < _inputWidth; x++) { for (int y = 0; y < _inputHeight; y++) { actualPixel = predictionTexture.GetPixel(x, y); // SDTV (BT.601) Y'UV conversion yuvPixel.r = actualPixel.r * 0.299f + actualPixel.g * 0.587f + actualPixel.b * 0.114f; // Y' luma component // Chrominance // U = r * -0.14713 + g * -0.28886 + b * 0.436 //yuvPixel.g = 0.0f; // V = r * 0.615 + g * -0.51499 + b * -0.10001 //yuvPixel.b = 0.0f; predictionTexture.SetPixel(x, y, yuvPixel); } } // Edge Detection Convolution methods: // Laplacian of the Gaussian (LoG) - https://en.wikipedia.org/wiki/Blob_detection#The_Laplacian_of_Gaussian // - Sobel-Feldman and Sharr operators - https://en.wikipedia.org/wiki/Sobel_operator // - Prewitt operator - https://en.wikipedia.org/wiki/Prewitt_operator // Kirch operator - https://en.wikipedia.org/wiki/Kirsch_operator Texture2D horzTexture = ConvolutionFilter.Apply(predictionTexture, ConvolutionFilter.Sobel3x3Horizontal); // ConvolutionFilter.Prewitt3x3Horizontal); Texture2D vertTexture = ConvolutionFilter.Apply(predictionTexture, ConvolutionFilter.Sobel3x3Vertical); // ConvolutionFilter.Prewitt3x3Vertical); Texture2D convolvedTexture = new Texture2D(_inputWidth, _inputHeight, predictionTexture.format, false); Color tempPixel = new Color(0.0f, 0.0f, 0.0f); for (int x = 0; x < _inputWidth; x++) { for (int y = 0; y < _inputHeight; y++) { Color horzPixel = horzTexture.GetPixel(x, y); Color vertPixel = vertTexture.GetPixel(x, y); tempPixel.r = Mathf.Sqrt((horzPixel.r * horzPixel.r) + (vertPixel.r * vertPixel.r)); tempPixel.g = tempPixel.r; // Mathf.Sqrt((horzPixel.g * horzPixel.g) + (vertPixel.g * vertPixel.g)); tempPixel.b = tempPixel.r; // Mathf.Sqrt((horzPixel.b * horzPixel.b) + (vertPixel.b * vertPixel.b)); convolvedTexture.SetPixel(x, y, tempPixel); } } predictionTexture.SetPixels(convolvedTexture.GetPixels()); predictionTexture.Apply(); // Transfer the RGB camera texture into ValueField2D fields for (int x = 0; x < _inputWidth; x++) { for (int y = 0; y < _inputHeight; y++) { actualPixel = predictionTexture.GetPixel(x, y); pixelPos.x = x; pixelPos.y = y; _inputField.setValue(pixelPos, actualPixel.r); previousImage[x, y] = sourceImage[x, y]; sourceImage[x, y] = actualPixel.r;// * 0.299f + actualPixel.g * 0.587f + actualPixel.b * 0.114f; } } // Encode scalar values from the car controller Steer = carController.CurrentSteerAngle / carController.m_MaximumSteerAngle; Accel = carController.AccelInput; Brake = carController.BrakeInput; pixelPos.x = 0; pixelPos.y = 0; _inputValues.setValue(pixelPos, Steer); // Setup the hierarchy input vector vectorvf inputVector = new vectorvf(); inputVector.Add(_inputField); inputVector.Add(_inputValues); // Step the hierarchy _hierarchy.activate(inputVector); if (Training) { _hierarchy.learn(inputVector); } // Grab the predictions vector vectorvf prediction = _hierarchy.getPredictions(); // Transfer the ValueField2D fields into the RGB prediction texture Color predictedPixel = new Color(); for (int x = 0; x < _inputWidth; x++) { for (int y = 0; y < _inputHeight; y++) { pixelPos.x = x; pixelPos.y = y; predictedPixel.r = prediction[0].getValue(pixelPos); predictedPixel.g = predictedPixel.r; // prediction[1].getValue(pixelPos); predictedPixel.b = predictedPixel.r; // prediction[2].getValue(pixelPos); predictionTexture.SetPixel(x, y, predictedPixel); predictedImage[x, y] = predictedPixel.r;// * 0.299f + predictedPixel.g * 0.587f + predictedPixel.b * 0.114f; } } predictionTexture.Apply(); // Wait for physics to settle if (_time < 1.0f) { _time += Time.deltaTime; // Apply hand brake carSteer = 0.0f; carAccel = 0.0f; carBrake = -1.0f; HandBrake = 1.0f; } else { // Release hand brake HandBrake = 0.0f; Accel = -1.0f; Brake = Accel; pixelPos.x = 0; pixelPos.y = 0; // Update the car controller PredictedSteer = prediction[1].getValue(pixelPos); PredictedAccel = Accel; PredictedBrake = Brake; carSteer = PredictedSteer;// * carController.m_MaximumSteerAngle; carAccel = PredictedAccel; carBrake = PredictedBrake; // Search along the spline for the closest point to the current car position float bestT = 0.0f, minDistance = 100000.0f; Vector3 carPosition = carController.gameObject.transform.localPosition; // When not training use the track spline BezierSpline spline = trackSpline; if (Training) { spline = splineList[SplineIndex]; } float totalDistance = 0.0f; for (float t = 0.0f; t <= 1.0f; t += 0.001f) { Vector3 position = spline.GetPoint(t); Vector3 positionPrev = spline.GetPoint(t - 0.001f); float distance = Vector3.Distance(position, carPosition); totalDistance += Vector3.Distance(position, positionPrev); if (distance <= minDistance) { minDistance = distance; bestT = t; } } // Reset car position and direction? if (Input.GetKeyUp(KeyCode.R) || carController.Collided) { if (ForcePredictionMode == false) { Training = true; } carController.ResetCollided(); // Spline 0 is usually set as the spline used to create the track SplineIndex = 0; Vector3 position = spline.GetPoint(bestT); carController.gameObject.transform.localPosition = position; Vector3 splineDirection = spline.GetDirection(bestT).normalized; carController.gameObject.transform.forward = -splineDirection; } // Determine the difference between the input image (t) and predicted image (t+1) CalculateNormalizedCrossCorrelation(); // Toggle training on iff too divergent? if (Training == false && ForcePredictionMode == false && NCC < 0.25f) { Training = true; } // Toggle training off iff quite confident? if (Training == true && NCC > 0.85f && LapCount >= initialTrainingLaps) { Training = false; } if (carController.CurrentSpeed < 2.0f) { Training = true; } if (Training) { _trainingCount++; } else { _predictingCount++; } if (Training && spline != null) { Vector3 carDirection = -carController.gameObject.transform.forward.normalized; Vector3 targetPosition = spline.GetPoint(bestT + SteerAhead / totalDistance); //Vector3 splineDirection = spline.GetDirection(bestT).normalized; Vector3 targetDirection = (targetPosition - carPosition).normalized; float angle = (1.0f - Vector3.Dot(carDirection, targetDirection));// * Mathf.Rad2Deg; Vector3 right = Vector3.Cross(carDirection, Vector3.up); float angle2 = Vector3.Dot(right, targetDirection); float newCarSteer = Mathf.Exp(256.0f * angle) - 1.0f; if (Mathf.Abs(minDistance) > 0.01f)//newCarSteer > Mathf.PI / 64.0f) { newCarSteer += angle2 * Mathf.Abs(minDistance); } if (angle2 > 0.0f) { newCarSteer = -newCarSteer; } if (newCarSteer > 1.0f) { newCarSteer = 1.0f; } else if (newCarSteer < -1.0f) { newCarSteer = -1.0f; } float steerBlend = 0.75f; carSteer = (steerBlend * newCarSteer) + ((1.0f - steerBlend) * carSteer); if (enableDebugLines) { debugLinePositions[0] = carController.gameObject.transform.localPosition; debugLinePositions[1] = debugLinePositions[0] + carDirection * 10.0f; debugLinePositions[2] = carController.gameObject.transform.localPosition; debugLinePositions[3] = debugLinePositions[2] + targetDirection * 10.0f; debugLine.SetPositions(debugLinePositions); } } float totalCount = _trainingCount + _predictingCount; if (totalCount == 0.0f) { TrainingPercent = 1.0f; PredictionPercent = 0.0f; } else { TrainingPercent = (float)_trainingCount / totalCount; PredictionPercent = (float)_predictingCount / totalCount; } if (bestT < prevBestT) { LapCount++; _trainingCount = 0; _predictingCount = 0; if ((LapCount % lapsPerSpline) == 0) { SplineIndex++; if (SplineIndex >= splineList.Length) { SplineIndex = 0; } } } prevBestT = bestT; } if (userControl) { // Control overides // pass the input to the car! float h = CrossPlatformInputManager.GetAxis("Horizontal"); float v = CrossPlatformInputManager.GetAxis("Vertical"); #if !MOBILE_INPUT float handbrake = CrossPlatformInputManager.GetAxis("Jump"); #endif carSteer = h; carAccel = v; carBrake = v; HandBrake = handbrake; } // Toggle training? if (Input.GetKeyUp(KeyCode.T)) { Training = !Training; ForcePredictionMode = false; } else // Force prediction mode? if (Input.GetKeyUp(KeyCode.F)) { Training = false; ForcePredictionMode = true; } // Save out the current state of the hierarchy? if (Input.GetKeyUp(KeyCode.O) && hierarchyFileName.Length > 0) { _hierarchy.save(_res.getComputeSystem(), hierarchyFileName); print("Saved OgmaNeo hierarchy to " + hierarchyFileName); } }
public Mesh CreateMesh() { Mesh mesh; mesh = new Mesh(); float scaling = 1f; float width = thickness / 2f; List <Vector3> vertList = new List <Vector3>(); List <int> triList = new List <int>(); List <Vector2> uvList = new List <Vector2>(); Vector3 upNormal = new Vector3(0, 0, 1); triList.AddRange(new int[] { 2, 1, 0, //start face 0, 3, 2 }); for (int s = 0; s < resolution; s++) { float t = ((float)s) / resolution; float futureT = ((float)s + 1) / resolution; Vector3 segmentStart = spline.GetPoint(t); Vector3 segmentEnd = spline.GetPoint(futureT); Vector3 segmentDirection = spline.GetVelocity(t) - spline.GetVelocity(futureT); segmentDirection.Normalize(); Vector3 segmentRight = Vector3.ProjectOnPlane(segmentDirection, upNormal); segmentRight *= width; //Vector3 offset = segmentRight * (width / 2) * scaling; Vector3 offset = Vector3.zero; Vector3 br = segmentRight + upNormal * width + offset; Vector3 tr = segmentRight + upNormal * -width + offset; Vector3 bl = -segmentRight + upNormal * width + offset; Vector3 tl = -segmentRight + upNormal * -width + offset; int curTriIdx = vertList.Count; Vector3[] segmentVerts = new Vector3[] { segmentStart + br, segmentStart + bl, segmentStart + tl, segmentStart + tr, }; vertList.AddRange(segmentVerts); Vector2[] uvs = new Vector2[] { new Vector2(0, 0), new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 1) }; uvList.AddRange(uvs); int[] segmentTriangles = new int[] { curTriIdx + 6, curTriIdx + 5, curTriIdx + 1, //left face curTriIdx + 1, curTriIdx + 2, curTriIdx + 6, curTriIdx + 7, curTriIdx + 3, curTriIdx + 0, //right face curTriIdx + 0, curTriIdx + 4, curTriIdx + 7, curTriIdx + 1, curTriIdx + 5, curTriIdx + 4, //top face curTriIdx + 4, curTriIdx + 0, curTriIdx + 1, curTriIdx + 3, curTriIdx + 7, curTriIdx + 6, //bottom face curTriIdx + 6, curTriIdx + 2, curTriIdx + 3 }; triList.AddRange(segmentTriangles); // final segment fenceposting: finish segment and add end face if (s == resolution - 1) { curTriIdx = vertList.Count; vertList.AddRange(new Vector3[] { segmentEnd + br, segmentEnd + bl, segmentEnd + tl, segmentEnd + tr }); uvList.AddRange(new Vector2[] { new Vector2(0, 0), new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 1) } ); triList.AddRange(new int[] { curTriIdx + 0, curTriIdx + 1, curTriIdx + 2, //end face curTriIdx + 2, curTriIdx + 3, curTriIdx + 0 }); } } mesh.vertices = vertList.ToArray(); mesh.triangles = triList.ToArray(); mesh.uv = uvList.ToArray(); mesh.RecalculateNormals(); mesh.RecalculateBounds(); return(mesh); }
public Vector3 getClosedLoopStartPosition() { return(m_bezierSpline.GetPoint(m_closedLoopStartPoint)); }
// Use this for initialization void Start() { t = 0; currentSpline = startingSpline; transform.position = currentSpline.GetPoint(t); transform.rotation = currentSpline.GetOrientation(t, Vector3.Lerp(currentSpline.startNode.transform.up, currentSpline.endNode.transform.up, t)); lastForward = transform.forward; }