void debugDrawSquare(Vector3 localSpaceVector, Color c) { Vector3 sll = localSpaceVector.Clone(); sll.x -= squareSideLength / 2; sll.y -= squareSideLength / 2; Vector3 slr = localSpaceVector.Clone(); slr.x += squareSideLength / 2; slr.y -= squareSideLength / 2; Vector3 sul = localSpaceVector.Clone(); sul.x -= squareSideLength / 2; sul.y += squareSideLength / 2; Vector3 sur = localSpaceVector.Clone(); sur.x += squareSideLength / 2; sur.y += squareSideLength / 2; debugDrawLineLocalCoord(sll, slr, c); debugDrawLineLocalCoord(slr, sur, c); debugDrawLineLocalCoord(sur, sul, c); debugDrawLineLocalCoord(sul, sll, c); }
public void CyclePositionedCorrectlyWithCollisions() { var gameConfig = new GameConfiguration(new CycleConfiguration(), new MapConfiguration()); var map = new Map(gameConfig.MapConfig); var startPosition = new Vector3(0, gameConfig.CycleConfig.Y_OFFSET, 0); var cycle = new Cycle(1, startPosition, new Vector3(1, 0, 0), Math.PI + Math.PI * .5, 0xff0000, map, gameConfig); var requestValidator = new RequestValidator(map); var newPosition = startPosition.Clone(); var collision = startPosition.Clone(); newPosition.x += gameConfig.MapConfig.FLOOR_TILE_SIZE.Width * 5; collision.x += gameConfig.MapConfig.FLOOR_TILE_SIZE.Width * 3; cycle.MovementController.RequestedPosition = newPosition; cycle.MovementController.HeadLocation = map.Utilities.ToMapLocation(cycle.MovementController.Position); map[map.Utilities.ToMapLocation(cycle.MovementController)] = -cycle.ID; map[map.Utilities.ToMapLocation(collision)] = 5; requestValidator.ValidateRequestedPosition(cycle); Assert.True(cycle.MovementController.Position.SameAs(collision)); map.Clear(); newPosition = startPosition.Clone(); newPosition.x += gameConfig.MapConfig.FLOOR_TILE_SIZE.Width; cycle.MovementController.Position = startPosition; cycle.MovementController.RequestedPosition = newPosition; map[map.Utilities.ToMapLocation(startPosition)] = -cycle.ID; map[map.Utilities.ToMapLocation(newPosition)] = 5; requestValidator.ValidateRequestedPosition(cycle); Assert.True(cycle.MovementController.Position.SameAs(newPosition)); map.Clear(); newPosition = startPosition.Clone(); newPosition.x += gameConfig.MapConfig.FLOOR_TILE_SIZE.Width; cycle.MovementController.Position = startPosition; cycle.MovementController.RequestedPosition = newPosition; map[map.Utilities.ToMapLocation(startPosition)] = -cycle.ID; map[map.Utilities.ToMapLocation(newPosition)] = 5; newPosition.x += gameConfig.MapConfig.FLOOR_TILE_SIZE.Width; map[map.Utilities.ToMapLocation(newPosition)] = 5; newPosition.x -= gameConfig.MapConfig.FLOOR_TILE_SIZE.Width; requestValidator.ValidateRequestedPosition(cycle); Assert.True(cycle.MovementController.Position.SameAs(newPosition)); map.Clear(); newPosition = map.Utilities.ToPosition(new MapLocation(23, 173), gameConfig.CycleConfig.Y_OFFSET); cycle.MovementController.Position = map.Utilities.ToPosition(new MapLocation(25, 173), gameConfig.CycleConfig.Y_OFFSET); cycle.MovementController.RequestedPosition = newPosition; cycle.MovementController.HeadLocation = map.Utilities.ToMapLocation(cycle.MovementController.Position); cycle.MovementController.Velocity = new Vector3(0, 0, -1); cycle.MovementController.Rotation = 0; map[map.Utilities.ToMapLocation(startPosition)] = -cycle.ID; map[new MapLocation(24, 173)] = 5; requestValidator.ValidateRequestedPosition(cycle); Assert.True(cycle.MovementController.Position.SameAs(map.Utilities.ToPosition(new MapLocation(24, 173), gameConfig.CycleConfig.Y_OFFSET))); }
/// <summary> /// builds a flattened 2D array of vertices like the following: /// /// 15--16--17--18--19 /// | | | | | /// 10--11--12--13--14 /// | | | | | /// 5---6---7---8---9 /// | | | | | /// 0---1---2---3---4 /// /// NOTE: <see cref="AddNeighbors"/> must be called after this method to /// ensure that we properly detect the correct neighbors /// </summary> private void GenerateVertices() { // start from the passed in _bottomLeft Vector3 and build list of QuadVerts int rows = Subdivisions + 2; int cols = rows; float colVertOffset = 0F; float rowVertOffset = 0F; colVertOffset = Size / (Subdivisions + 1F); rowVertOffset = Size / (Subdivisions + 1F); float uvScalar = 1 / (4 * Face.Size); float xBottomLeftOffset = -Size / 2F; float yBottomLeftOffset = -Size / 2F; float zBottomLeftOffset = 0F; Vector3 bottomLeftCorner = new Vector3(xBottomLeftOffset, yBottomLeftOffset, zBottomLeftOffset); for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { int index = FlatArray.GetIndexFromRowCol(row, col, cols); Vector3 v = new Vector3((col * colVertOffset) + bottomLeftCorner.x, (row * rowVertOffset) + bottomLeftCorner.y, bottomLeftCorner.z); if (index == 0) { BottomLeft = v.Clone(); } if (index == FlatArray.GetBottomRightIndex(cols)) { BottomRight = v.Clone(); } if (index == FlatArray.GetTopLeftIndex(rows, cols)) { TopLeft = v.Clone(); } if (index == FlatArray.GetTopRightIndex(rows, cols)) { TopRight = v.Clone(); } Vector3 scaledUV = Face.ToLocalVert(ToWorldVert(v)) * uvScalar; var uvOffset = Face.GetUVOffset(); Vector2 uv = new Vector2(uvOffset.x + scaledUV.x, uvOffset.y + scaledUV.y); // set elevation v = GetInverseOffsetFromRoot(Face.ApplyElevation(GetOffsetFromRoot(v), uv)); Vertices[index] = v; UVs[index] = uv; } } DistanceTestCentre = GetInverseOffsetFromRoot(Face.ApplyElevation(GetOffsetFromRoot(CentrePoint), Face.GetUVOffset())); }
private void OnPlayerAngle(NetPacketBase packet) { var startPositionX = packet.Read <float>(); var startPositionY = packet.Read <float>(); var startPositionZ = packet.Read <float>(); var startPosition = new Vector3(startPositionX, startPositionY, startPositionZ); var directionX = packet.Read <float>(); var directionY = packet.Read <float>(); var directionZ = packet.Read <float>(); var directionVector = new Vector3(directionX, directionY, directionZ); var angle = packet.Read <float>(); var angleY = packet.Read <float>(); float flySpeed = packet.Read <float>(); this.Player.TurnAngle = packet.Read <float>(); var tick = packet.Read <long>(); this.Player.Angle = angle; this.Player.AngleFly = angle; this.Player.Position = startPosition.Clone(); if (directionVector.IsZero()) { this.Player.DestinationPosition = this.Player.Position.Clone(); } this.Player.SendMoverAngle(directionVector, tick, this.Player.TurnAngle); }
private void OnPlayerMoved2(NetPacketBase packet) { var startPositionX = packet.Read <float>(); var startPositionY = packet.Read <float>(); var startPositionZ = packet.Read <float>(); var startPosition = new Vector3(startPositionX, startPositionY, startPositionZ); var directionX = packet.Read <float>(); var directionY = packet.Read <float>(); var directionZ = packet.Read <float>(); var directionVector = new Vector3(directionX, directionY, directionZ); if (directionVector.IsZero()) { this.Player.DestinationPosition = startPosition.Clone(); } this.Player.Angle = packet.Read <float>(); this.Player.AngleFly = packet.Read <float>(); var flySpeed = packet.Read <float>(); var turnAngle = packet.Read <float>(); this.Player.MovingFlags = (ObjectState)packet.Read <uint>(); this.Player.MotionFlags = (StateFlags)packet.Read <int>(); this.Player.ActionFlags = packet.Read <int>(); var motionEx = packet.Read <int>(); var loop = packet.Read <int>(); var motionOption = packet.Read <int>(); var tick = packet.Read <long>(); var frame = packet.Read <byte>(); this.Player.IsFlying = this.Player.MovingFlags.HasFlag(ObjectState.OBJSTA_FMOVE); this.Player.SendMoverMoved(directionVector, motionEx, loop, motionOption, tick, frame, turnAngle); }
public static Vector3 GetNormalized(this Vector3 vec) { var v = vec.Clone(); v.Normalize(); return(v); }
private void OnClick_Card(GameObject obj) { if (!CanClickTween) { return; } if (ClickedObject && ClickedObject != this) { ClickedObject.OnTween_BackSolt(); } ClickedObject = this; if (!IsClicked) { IsClicked = true; mOldPostion = transform.position; Vector3 endPos = SlotPostion.Clone(); endPos.y += 0.045f; transform.DOMove(endPos, 0.1f); } else { OnTween_BackSolt(); } }
public Vector3 GetLinePosition(Vector3 currentPosition) { Vector3 currentVelocity; currentPosition = currentPosition.Clone(); // If our velocity was zero then reset position to where our head location is if (Velocity.IsZero()) { return(_map.Utilities.ToPosition(HeadLocation, currentPosition.y)); } else { currentVelocity = Velocity; } if (currentVelocity.z != 0) { currentPosition.z = stabilizeValue(currentPosition.z, currentVelocity.z); } else if (currentVelocity.x != 0) { currentPosition.x = stabilizeValue(currentPosition.x, currentVelocity.x); } return(currentPosition); }
public StagePositionConfig Clone() { StagePositionConfig item = new StagePositionConfig(); /** 关卡编号 */ item.stageId = stageId; /** 建筑编号 */ item.index = index; /** 坐标 */ item.position = position.Clone(); /** 初始兵力 (-1通过公式计算;其他直接读配置) */ item.hp = hp; /** 势力ID */ item.legionId = legionId; /** 单位类型 */ item.unitType = unitType; /** 建筑类型 */ item.buildType = buildType; /** 建筑等级 */ item.level = level; /** 不同类型,建筑数据UID */ item.buildUid = buildUid; /** 英雄上阵优先级 */ item.settledPriority = settledPriority; item.name = name; item.stageName = stageName; return(item); }
private void Tween_AddExp(bool to = true) { if (null != mExpTween) { return; } m_Panel.panAddPower.gameObject.SetActive(true); Vector3 toPos = AddExpPan_InitPosition; Vector3 fromPos = toPos.Clone(); if (to) { fromPos.y -= 0.8f; m_Panel.panAddPower.position = fromPos; } else { toPos.y -= 0.8f; } mShowExpan = to; mExpTween = m_Panel.panAddPower.DOMoveY(toPos.y, 0.5f).OnComplete(() => { mExpTween = null; }); }
void Start() { gameObject.AddComponent <MeshFilter>(); gameObject.AddComponent <MeshRenderer>(); Mesh mesh = GetComponent <MeshFilter>().mesh; Vector3[] vertices = new Vector3[4]; vertices[0] = new Vector3(0, 0); vertices[1] = new Vector3(1, 0); vertices[2] = new Vector3(1, 1); vertices[3] = new Vector3(0, 1); baseVertices = vertices; int[] triangles = new int[2 * 3]; triangles[0 * 3 + 0] = 0; triangles[0 * 3 + 1] = 1; triangles[0 * 3 + 2] = 2; triangles[1 * 3 + 0] = 0; triangles[1 * 3 + 1] = 2; triangles[1 * 3 + 2] = 3; mesh.vertices = (Vector3[])vertices.Clone(); mesh.triangles = triangles; }
private void OnPlayerBehavior(NetPacketBase packet) { var startPositionX = packet.Read <float>(); var startPositionY = packet.Read <float>(); var startPositionZ = packet.Read <float>(); var startPosition = new Vector3(startPositionX, startPositionY, startPositionZ); var directionX = packet.Read <float>(); var directionY = packet.Read <float>(); var directionZ = packet.Read <float>(); var directionVector = new Vector3(directionX, directionY, directionZ); var angle = packet.Read <float>(); this.Player.MovingFlags = (ObjectState)packet.Read <uint>(); this.Player.MotionFlags = (StateFlags)packet.Read <int>(); this.Player.ActionFlags = packet.Read <int>(); var motionEx = packet.Read <int>(); var loop = packet.Read <int>(); var motionOption = packet.Read <int>(); var tick = packet.Read <long>(); this.Player.Position = startPosition.Clone(); this.Player.Position += directionVector; this.Player.DestinationPosition.Reset(); this.Player.IsMovingWithKeyboard = this.Player.MovingFlags.HasFlag(ObjectState.OBJSTA_FMOVE); this.Player.SendMoverBehavior(directionVector, motionEx, loop, motionOption, tick); }
/// <summary> /// Creates a sample of (N+2) points (i.e., N + start and end points) of /// the current curve. Also calculates the length estimate. /// </summary> /// <returns>The sample.</returns> /// <param name="N">N.</param> public override Vector3[] Sample(int N = 100) { lastSampleSize = N; if (N == 0) { return(new Vector3[] { GetPoint(0), GetPoint(1) }); } var sample = new Vector3[N + 2]; var delta = 1.0f / (N + 1.0f); length = 0.0f; sampleParameters = new float[N + 2]; sampleLengths = new float[N + 2]; for (var i = 0; i < (N + 2); i++) { sample[i] = GetPoint(i * delta); sampleParameters[i] = i * delta; if (i > 0) { length += (sample[i] - sample[i - 1]).magnitude; } sampleLengths[i] = length; } isSampleDirty = false; return((Vector3[])sample.Clone()); }
void Start() { gameObject.AddComponent<MeshFilter>(); gameObject.AddComponent<MeshRenderer>(); Mesh mesh = GetComponent<MeshFilter>().mesh; Vector3[] vertices = new Vector3[4]; vertices[0] = new Vector3(0, 0); vertices[1] = new Vector3(1, 0); vertices[2] = new Vector3(1, 1); vertices[3] = new Vector3(0, 1); baseVertices = vertices; int[] triangles = new int[2 * 3]; triangles[0 * 3 + 0] = 0; triangles[0 * 3 + 1] = 1; triangles[0 * 3 + 2] = 2; triangles[1 * 3 + 0] = 0; triangles[1 * 3 + 1] = 2; triangles[1 * 3 + 2] = 3; mesh.vertices = (Vector3[]) vertices.Clone(); mesh.triangles = triangles; }
public static Vector3 PointRadian(Vector3 o, float radian, float length) { Vector3 p = o.Clone(); p.x = o.x + Mathf.Sin(radian) * length; p.z = o.z + Mathf.Cos(radian) * length; return(p); }
/// <summary> /// Moves the monster to a position. /// </summary> /// <param name="monster"></param> /// <param name="destPosition"></param> private void MoveToPosition(IMonsterEntity monster, Vector3 destPosition) { monster.Timers.NextMoveTime = Time.TimeInSeconds() + RandomHelper.LongRandom(8, 20); monster.MovableComponent.DestinationPosition = destPosition.Clone(); monster.Object.Angle = Vector3.AngleBetween(monster.Object.Position, destPosition); WorldPacketFactory.SendDestinationPosition(monster); }
public Ray(Vector3 o, Vector3 d, double tmin = 0.0, double tmax = double.PositiveInfinity, int depth = 0) { this.o = o.Clone(); this.d = d.Clone(); this.tmin = tmin; this.tmax = tmax; this.depth = depth; }
public object Clone() { Cmd clone = (Cmd)MemberwiseClone(); clone.position = position.Clone(); clone.dir = dir.Clone(); return(clone); }
/// <summary> /// get a point which is from o direction of radian`s distance /// </summary> public static Vector3 Get3dPointRadian(Vector3 o, float radian, float distance) { Vector3 p = o.Clone(); p.x = o.x + Mathf.Sin(radian) * distance; p.z = o.z + Mathf.Cos(radian) * distance; return(p); }
/// <summary> /// Moves the monster to a position. /// </summary> /// <param name="monster"></param> /// <param name="destPosition"></param> private void MoveToPosition(IMonsterEntity monster, Vector3 destPosition) { monster.Object.Angle = Vector3.AngleBetween(monster.Object.Position, destPosition); monster.Object.MovingFlags = ObjectState.OBJSTA_FMOVE; monster.Moves.DestinationPosition = destPosition.Clone(); WorldPacketFactory.SendDestinationPosition(monster); WorldPacketFactory.SendDestinationAngle(monster, false); }
private Vector3[] mNormalAtVertices = null; // may not be there (only present for triangles created from a mesh) #endregion Fields #region Constructors /// <summary> /// Constructs from given positions, normal, and uv then intialize for intersection computation. /// </summary> /// <param name="parser"></param> protected RTTriangle(Vector3[] vertices, Vector3[] normalAtVertex, Vector2[] uvAtVertex, int material) { mType = RTGeometryType.Triangle; mMaterialIndex = material; mVertices = (Vector3[])vertices.Clone(); if (null != normalAtVertex) mNormalAtVertices = (Vector3[])normalAtVertex.Clone(); mVertexUV = (Vector2[])uvAtVertex.Clone(); InitializeTriangle(); }
protected void OpenList() { popupButton.Interactable = false; if (useMask) { mask.gameObject.SetActive(true); } // bg.gameObject.SetActive(true); container.gameObject.SetActive(true); tipParent.gameObject.SetActive(false); List <RectTransform> list = GetList(); // bg.sizeDelta = bg.sizeDelta.SetX((gap + w) * list.Count + 100f); // bg.localScale = new Vector3(0.0f, 1f, 1f); // iTween.ScaleTo(bg.gameObject, iTween.Hash("time",0.15F, // "scale", Vector3.one, // "easetype", iTween.EaseType.easeOutBack)); // iTween.Stop(); for (int i = 0; i < list.Count; i++) { RectTransform item = list[i]; Image image = item.GetComponent <Image>(); image.color = image.color.Clone().SetAlhpa(0f); iTween.FadeTo(item.gameObject, iTween.Hash( "time", 0.2f, "alpha", 1F)); Vector3 position = item.localPosition; //position.x = x0 + (w + gap) * i; //item.localPosition = position.Clone().SetX(x0); position.y = y0 + (h + gap) * i; item.localPosition = position.Clone().SetY(y0); iTween.MoveTo(item.gameObject, iTween.Hash("delay", 0.01f, "time", 0.2f, "islocal", true, "position", position, "easetype", iTween.EaseType.easeOutBack )); } Invoke("OpenListComplete", 0.2F); }
public void GetLevelData() { lvlExit.levelBuild = ""; Vector3[] v3ObjectsRotations = new Vector3[iNumberOfObjects]; Color[] clrObjects = new Color[iNumberOfColors]; bool[] bMovementObjects = new bool[iNumberOfMovementObjects]; int iObjIndex = 0, iClrIndex = 0, iObjMoveIndex = 0; for (int i = 0; i < tiles.Length; i++) { lvlExit.levelBuild += ((int)tiles[i].GetComponent <Tile>().ttTile).ToString() + MMConstants.LEVEL_SEPARATOR; if (MMUtils.IsScenarioObject(tiles[i].GetComponent <Tile>().ttTile)) { v3ObjectsRotations[iObjIndex] = tiles[i].transform.rotation.eulerAngles; iObjIndex++; } if (MMUtils.IsColorObject(tiles[i].GetComponent <Tile>().ttTile)) { clrObjects[iClrIndex] = tiles[i].GetComponent <Tile>().clrObject; iClrIndex++; } if (MMUtils.IsPushableObject(tiles[i].GetComponent <Tile>().ttTile)) { bMovementObjects[iObjMoveIndex] = tiles[i].GetComponent <Tile>().bMovementOn; iObjMoveIndex++; } } lvlExit.objColor = new Color[iNumberOfColors]; lvlExit.objColor = (Color[])clrObjects.Clone(); lvlExit.objRotation = new Vector3[iNumberOfObjects]; lvlExit.objRotation = (Vector3[])v3ObjectsRotations.Clone(); lvlExit.objMovementEnabled = new bool[iNumberOfMovementObjects]; lvlExit.objMovementEnabled = (bool[])bMovementObjects.Clone(); lvlExit.levelBuild = lvlExit.levelBuild.Substring(0, lvlExit.levelBuild.Length - 1); lvlExit.MaxSize = iTileSize; #if UNITY_EDITOR AssetDatabase.SaveAssets(); EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); EditorUtility.SetDirty(lvlExit); #endif print("DATA GENERATED!"); }
/// <summary>平滑的朝向某物体</summary> public static void SmoothLookAt(Transform self, Vector3 target, bool smooth = true, float damping = 6.0f) { if (smooth) { //if (target == self.position) return; Quaternion rotation = Quaternion.LookRotation(target - self.position); self.rotation = Quaternion.Slerp(self.rotation, rotation, TimerManager.DeltaTime * damping); } else { self.rotation = Quaternion.FromToRotation(-Vector3.forward, (target.Clone() - self.position).normalized); } }
public void Vector3Clone() { tlog.Debug(tag, $"Vector3Clone START"); var testingTarget = new Vector3(10.0f, 20.0f, 30.0f); Assert.IsNotNull(testingTarget, "Can't create success object Vector3"); Assert.IsInstanceOf <Vector3>(testingTarget, "Should be an instance of Vector3 type."); var result = testingTarget.Clone(); Assert.IsInstanceOf <Vector3>(result, "Should be an instance of Vector3 type."); testingTarget.Dispose(); tlog.Debug(tag, $"Vector3Clone END (OK)"); }
public void CyclePositionedCorrectlyInBoundsAndColliding() { var gameConfig = new GameConfiguration(new CycleConfiguration(), new MapConfiguration()); var map = new Map(gameConfig.MapConfig); var startPosition = new Vector3(0, gameConfig.CycleConfig.Y_OFFSET, 0); var cycle = new Cycle(1, startPosition, new Vector3(1, 0, 0), Math.PI + Math.PI * .5, 0xff0000, map, gameConfig); var requestValidator = new RequestValidator(map); var collision = startPosition.Clone(); collision.x = gameConfig.MapConfig.MAP_SIZE.Width * .5 - gameConfig.MapConfig.FLOOR_TILE_SIZE.Width * 3; cycle.MovementController.RequestedPosition = new Vector3(gameConfig.MapConfig.MAP_SIZE.Width * .5 + gameConfig.MapConfig.FLOOR_TILE_SIZE.Width * 10, gameConfig.CycleConfig.Y_OFFSET, 0); cycle.MovementController.HeadLocation = map.Utilities.ToMapLocation(cycle.MovementController.Position); map[map.Utilities.ToMapLocation(startPosition)] = -cycle.ID; map[map.Utilities.ToMapLocation(collision)] = 5; requestValidator.ValidateRequestedPosition(cycle); Assert.True(cycle.MovementController.Position.SameAs(collision)); }
/// <summary> /// Approximate a curved face with recursively sub-divided triangles. /// </summary> /// <param name="v1"></param> /// <param name="v2"></param> /// <param name="v3"></param> private void Make(Vector3 v1, Vector3 v2, Vector3 v3) { var face = new Face3(((UserData)v1.UserData).index, ((UserData)v2.UserData).index, ((UserData)v3.UserData).index); face.VertexNormals.Add((Vector3)v1.Clone()); face.VertexNormals.Add((Vector3)v2.Clone()); face.VertexNormals.Add((Vector3)v3.Clone()); this.Faces.Add(face); _centroid.Copy(v1).Add(v2).Add(v3).DivideScalar(3); var azi = Azimuth(_centroid); this.FaceVertexUvs[0].Add(new List <Vector2> { CorrectUV(((UserData)v1.UserData).uv, v1, azi), CorrectUV(((UserData)v2.UserData).uv, v2, azi), CorrectUV(((UserData)v2.UserData).uv, v3, azi) }); }
private void OnMoveByKeyboard(NetPacketBase packet) { this.Player.IsFollowing = false; var startPositionX = packet.Read <float>(); var startPositionY = packet.Read <float>(); var startPositionZ = packet.Read <float>(); var startPosition = new Vector3(startPositionX, startPositionY, startPositionZ); var directionX = packet.Read <float>(); var directionY = packet.Read <float>(); var directionZ = packet.Read <float>(); var directionVector = new Vector3(directionX, directionY, directionZ); this.Player.Position = startPosition.Clone(); this.Player.Position += directionVector; this.Player.Angle = packet.Read <float>(); this.Player.MovingFlags = (ObjectState)packet.Read <uint>(); this.Player.MotionFlags = (StateFlags)packet.Read <int>(); this.Player.ActionFlags = packet.Read <int>(); var motionEx = packet.Read <int>(); var loop = packet.Read <int>(); var motionOption = packet.Read <int>(); var tick = packet.Read <long>(); this.Player.DestinationPosition.Reset(); if (this.Player.MovingFlags.HasFlag(ObjectState.OBJSTA_FMOVE) || this.Player.MovingFlags.HasFlag(ObjectState.OBJSTA_BMOVE)) { this.Player.IsMovingWithKeyboard = true; } else { this.Player.IsMovingWithKeyboard = false; } this.Player.DestinationPosition = this.Player.Position.Clone(); this.Player.SendMoveByKeyboard(directionVector, motionEx, loop, motionOption, tick); }
public UnitData Clone() { UnitData n = new UnitData(); n.id = id; n.name = name; n.unitType = unitType; n.buildType = buildType; n.legionId = legionId; n.level = level; n.position = position.Clone(); n.avatarId = avatarId; n.props.PropAdd(props); n._radius = _radius; if (we_BuildConfigData != null) { n.we_BuildConfigData = we_BuildConfigData.Clone(); } n.buildConfig = buildConfig; return(n); }
private static bool GetVRPlatformHelperVector(out Vector3 position, out Vector3 rotation) { position = Vector3.zero; rotation = Vector3.zero; if (XRSettings.loadedDeviceName == "Oculus") { position = addPosOculus.Clone(); rotation = addRotOculus.Clone(); return(true); } if (XRSettings.loadedDeviceName == "OpenVR") { OpenVRHelper[] vrHelpers = Resources.FindObjectsOfTypeAll <OpenVRHelper>(); foreach (OpenVRHelper vrHelper in vrHelpers) { if (vrHelper.gameObject.activeInHierarchy) { if (vrHelper.GetField <OpenVRHelper.VRControllerManufacturerName, OpenVRHelper>("_vrControllerManufacturerName") == OpenVRHelper.VRControllerManufacturerName.Valve) { position = addPosViveIndex.Clone(); rotation = addRotViveIndex.Clone(); } else { position = addPosOpenVR.Clone(); rotation = addRotOpenVR.Clone(); } return(true); } } } return(false); }
public static void xGetDegree(ref float pfAngXZ, /* ref float pfAngH,*/ Vector3 vDist) { Vector3 vDistXZ = vDist.Clone(); //Helper.CopyVector(vDist, ref vDistXZ); vDistXZ.Y = 0; float fAngXZ = MathHelper.ToDegree((float)Math.Atan2(vDist.X, -vDist.Z)); // ¿ì¼± XZÆò¸éÀÇ °¢µµ¸¦ ¸ÕÀú ±¸ÇÔ float fLenXZ = vDistXZ.Length; // yÁÂÇ¥¸¦ ¹«½ÃÇÑ XZÆò¸é¿¡¼ÀÇ ±æÀ̸¦ ±¸ÇÔ. //float fAngH = ToDegree((float)Math.Atan2(fLenXZ, vDist.fPosY)); // XZÆò¸éÀÇ ±æÀÌ¿Í y³ôÀÌ°£ÀÇ °¢µµ¸¦ ±¸ÇÔ. //fAngH -= 90.0f; if (fAngXZ < 0) { fAngXZ += 360; } else if (fAngXZ >= 360) { fAngXZ -= 360; } pfAngXZ = fAngXZ; //pfAngH = fAngH; }
/// <summary> /// Transforms a poly with the provided matrix /// </summary> public static Vector3[] Transform(Matrix mat, Vector3[] poly) { Vector3[] ret = (Vector3[])poly.Clone(); Vector3.Transform(ret, ref mat, ret); return ret; }
/// <summary> /// Transforms a poly with the current matrices and viewport. Useful for perspective projection matrices /// </summary> public Vector3[] TransformCurrent(Vector3[] poly) { Vector3[] ret = (Vector3[])poly.Clone(); for(int i=0;i<ret.Length;i++) { ret[i] = Device.Viewport.Project(ret[i], Matrices.projection, Matrices.view, Matrices.world); } return ret; }
void UpdateFairing() { ProceduralPart ppart = PPart; if (useFairing && ppart != null) { ProceduralAbstractSoRShape shape = ppart.CurrentShape as ProceduralAbstractSoRShape; if (shape != null) { Vector3[] topEndcapVerticies = shape.GetEndcapVerticies(true); Vector3[] topInner = new Vector3[topEndcapVerticies.Length + 1]; topEndcapVerticies.CopyTo(topInner, 0); topInner[topEndcapVerticies.Length] = topEndcapVerticies[0]; int vertCount = topInner.Length; //foreach (Vector3 v in topInner) // Debug.Log(v); Vector3[] topOuter = (Vector3[])topInner.Clone(); for (int i = 0; i < vertCount; ++i) { float r = topInner[i].magnitude; float r_ = r + fairingThickness; float scaleFactor = r_ / r; topOuter[i].x *= scaleFactor; topOuter[i].z *= scaleFactor; } TextureScale.x = topOuter[0].magnitude * 2 * Mathf.PI; Vector3[] sideTop = (Vector3[])topOuter.Clone(); Vector3[] sideBottom = (Vector3[])sideTop.Clone(); Vector3[] bottomInner = (Vector3[])topInner.Clone(); Vector3[] bottomOuter = (Vector3[])topOuter.Clone(); for (int i = 0; i < vertCount; ++i) { if (bottomNode != null) { sideBottom[i].y = bottomNode.position.y; bottomInner[i].y = bottomNode.position.y; bottomOuter[i].y = bottomNode.position.y; } } TextureScale.y = Mathf.Abs(topOuter[0].y - bottomOuter[0].y); Vector3[] innerSideTop = (Vector3[])topInner.Clone(); Vector3[] innerSideBottom = (Vector3[])bottomInner.Clone(); int topInnerStart = 0; int topOuterStart = topInnerStart + vertCount; int sideTopStart = topOuterStart + vertCount; int sideBottomStart = sideTopStart + vertCount; int bottomInnerStart = sideBottomStart + vertCount; int bottomOuterStart = bottomInnerStart + vertCount; int innerSideTopStart = bottomOuterStart + vertCount; int innerSideBottomStart = innerSideTopStart + vertCount; UncheckedMesh m = new UncheckedMesh(vertCount * 8, vertCount * 8 * 6); //int tri = 0; for (int i = 0; i < vertCount; ++i) { m.verticies[topInnerStart + i] = topInner[i]; m.verticies[topOuterStart + i] = topOuter[i]; m.verticies[sideTopStart + i] = sideTop[i]; m.verticies[sideBottomStart + i] = sideBottom[i]; m.verticies[bottomInnerStart + i] = bottomInner[i]; m.verticies[bottomOuterStart + i] = bottomOuter[i]; m.verticies[innerSideTopStart + i] = innerSideTop[i]; m.verticies[innerSideBottomStart + i] = innerSideBottom[i]; m.normals[topInnerStart + i] = new Vector3(0.0f, 1.0f, 0.0f); m.normals[topOuterStart + i] = new Vector3(0.0f, 1.0f, 0.0f); m.normals[sideTopStart + i] = m.verticies[sideTopStart + i].xz().normalized; m.normals[sideBottomStart + i] = m.verticies[sideBottomStart + i].xz().normalized; m.normals[bottomInnerStart + i] = new Vector3(0.0f, -1.0f, 0.0f); m.normals[bottomOuterStart + i] = new Vector3(0.0f, -1.0f, 0.0f); m.normals[innerSideTopStart + i] = -m.verticies[innerSideTopStart + i].xz().normalized; m.normals[innerSideBottomStart + i] = -m.verticies[innerSideBottomStart + i].xz().normalized; m.uv[topInnerStart + i] = new Vector2(Mathf.InverseLerp(0, vertCount - 1, i), 0.0f); m.uv[topOuterStart + i] = new Vector2(Mathf.InverseLerp(0, vertCount - 1, i), 1.0f); m.uv[sideTopStart + i] = new Vector2(Mathf.InverseLerp(0, vertCount - 1, i), 1.0f); m.uv[sideBottomStart + i] = new Vector2(Mathf.InverseLerp(0, vertCount - 1, i), 0.0f); m.uv[bottomInnerStart + i] = new Vector2(Mathf.InverseLerp(0, vertCount - 1, i), 0.0f); m.uv[bottomOuterStart + i] = new Vector2(Mathf.InverseLerp(0, vertCount - 1, i), 1.0f); m.uv[innerSideTopStart + i] = new Vector2(Mathf.InverseLerp(0, vertCount - 1, i), 0.0f); m.uv[innerSideBottomStart + i] = new Vector2(Mathf.InverseLerp(0, vertCount - 1, i), 1.0f); m.tangents[topInnerStart + i] = Vector3.Cross(m.normals[topInnerStart + i], m.verticies[topInnerStart + i]).xz().normalized.toVec4(-1); m.tangents[topOuterStart + i] = Vector3.Cross(m.normals[topOuterStart + i], m.verticies[topOuterStart + i]).xz().normalized.toVec4(-1); m.tangents[sideTopStart + i] = Vector3.Cross(m.normals[sideTopStart + i], new Vector3(0, 1, 0)).normalized.toVec4(-1); m.tangents[sideBottomStart + i] = Vector3.Cross(m.normals[sideTopStart + i], new Vector3(0, 1, 0)).normalized.toVec4(-1); m.tangents[bottomInnerStart + i] = Vector3.Cross(m.normals[bottomInnerStart + i], m.verticies[topInnerStart + i]).xz().normalized.toVec4(-1); m.tangents[bottomOuterStart + i] = Vector3.Cross(m.normals[bottomOuterStart + i], m.verticies[topOuterStart + i]).xz().normalized.toVec4(-1); m.tangents[innerSideTopStart + i] = Vector3.Cross(m.normals[innerSideTopStart + i], new Vector3(0, 1, 0)).normalized.toVec4(-1); m.tangents[innerSideBottomStart + i] = Vector3.Cross(m.normals[innerSideTopStart + i], new Vector3(0, 1, 0)).normalized.toVec4(-1); //Debug.Log(i +" uv: " + Mathf.InverseLerp(0, vertCount - 1, i)); } int triangleOffset = 0; triangleOffset = ConnectRings(m, topInnerStart, topOuterStart, vertCount, 0); triangleOffset = ConnectRings(m, sideTopStart, sideBottomStart, vertCount, triangleOffset); triangleOffset = ConnectRings(m, bottomOuterStart, bottomInnerStart, vertCount, triangleOffset); triangleOffset = ConnectRings(m, innerSideBottomStart, innerSideTopStart, vertCount, triangleOffset); if (fairingMesh != null) { m.WriteTo(fairingMesh); fairingMesh.RecalculateNormals(); } else Debug.Log("no fairing mesh"); } oldTextureSet = null; UpdateTexture(); } }
/// <summary> /// Initializes a new instance of the <see cref="Posit"/> class. /// </summary> /// /// <param name="model">Array of vectors containing coordinates of four real model's point.</param> /// <param name="focalLength">Effective focal length of the camera used to capture the model.</param> /// /// <exception cref="ArgumentException">The model must have 4 points.</exception> /// public CoplanarPosit( Vector3[] model, float focalLength ) { if ( model.Length != 4 ) { throw new ArgumentException( "The model must have 4 points." ); } this.focalLength = focalLength; modelPoints = (Vector3[]) model.Clone( ); // compute model vectors modelVectors = Matrix3x3.CreateFromRows( model[1] - model[0], model[2] - model[0], model[3] - model[0] ); // compute pseudo inverse of the model matrix Matrix3x3 u, v; Vector3 e; modelVectors.SVD( out u, out e, out v ); modelPseudoInverse = v * Matrix3x3.CreateDiagonal( e.Inverse( ) ) * u.Transpose( ); // computer unit vector normal to the model modelNormal = v.GetColumn( e.MinIndex ); }
bool AIUse_SelectCircle(SkillOperateData skillData) { List <UnitCtl> soliderList = War.scene.soliderList; List <Vector3> pointTotals = new List <Vector3>(); List <Vector3> pointCenters = new List <Vector3>(); List <int> pointCounts = new List <int>(); float distance = skillData.skillConfig.radius * 2; for (int i = 0; i < soliderList.Count; i++) { UnitCtl entity = soliderList[i]; RelationType relationType = entity.unitData.GetRelation(skillData.heroData.legionData.legionId); if (skillData.skillConfig.relation.RValue(relationType) == false) { continue; } Vector3 pos = entity.transform.position; bool hasContain = false; for (int index = 0; index < pointCenters.Count; index++) { Vector3 center = pointCenters[index]; if (Vector3.Distance(center, pos) <= distance) { pointTotals[index] += pos; pointCounts[index] += 1; pointCenters[index] = pointTotals[index] / pointCounts[index]; hasContain = true; break; } } if (hasContain == false) { pointTotals.Add(pos.Clone()); pointCenters.Add(pos.Clone()); pointCounts.Add(1); } } int maxIndex = -1; int maxCount = -1; for (int index = 0; index < pointCounts.Count; index++) { if (maxCount < pointCounts[index]) { maxCount = pointCounts[index]; maxIndex = index; } } if (maxIndex != -1) { skillData.receivePosition = pointCenters[maxIndex]; // War.skillUse.selectCircleView.transform.position = skillData.receivePosition; // War.skillUse.selectCircleView.Radius = skillData.skillConfig.radius; // War.skillUse.selectCircleView.gameObject.SetActive(true); return(true); } return(false); }
private Vector3[] getTopLinePoints(Vector3[] points) { Vector3[] secondPoints = (Vector3[])points.Clone(); for (int i = 0; i < secondPoints.Length; i++) { secondPoints[i].y = secondPoints[i].y + getVerticalCollisionDistance(); } return secondPoints; }
public BezierCurve(Vector3[] points) { allPoints = new Vector3[points.Length][]; allPoints[0] = (Vector3[])points.Clone(); for (int i = points.Length-1, j = 1; j < allPoints.Length; --i, j++) { allPoints[j] = new Vector3[i]; } }
public void SetObject( Vector3[] vertices, Color[] colors, int[,] ribs ) { if ( vertices.Length != colors.Length ) { throw new ArgumentException( "Number of colors must be equal to number of vertices." ); } if ( ribs.GetLength( 1 ) != 2 ) { throw new ArgumentException( "Ribs array must have 2 coordinates per rib." ); } this.objectPoints = (Vector3[]) vertices.Clone( ); this.colors = (Color[]) colors.Clone( ); this.lines = (int[,]) ribs.Clone( ); Recalculate( ); }
//Clone an array and the inner array Vector3[][] CloneList(Vector3[][] arrayToClone) { //First clone the outer array Vector3[][] newArray = arrayToClone.Clone() as Vector3[][]; //Then clone the inner arrays for (int i = 0; i < newArray.Length; i++) { newArray[i] = newArray[i].Clone() as Vector3[]; } return newArray; }
/// <summary> /// Initializes a new instance of the <see cref="Posit"/> class. /// </summary> /// /// <param name="model">Array of vectors containing coordinates of four real model's point (points /// must not be on the same plane).</param> /// <param name="focalLength">Effective focal length of the camera used to capture the model.</param> /// /// <exception cref="ArgumentException">The model must have 4 points.</exception> /// public Posit( Vector3[] model, float focalLength ) { if ( model.Length != 4 ) { throw new ArgumentException( "The model must have 4 points." ); } this.focalLength = focalLength; modelPoints = (Vector3[]) model.Clone( ); // compute model vectors modelVectors = Matrix3x3.CreateFromRows( model[1] - model[0], model[2] - model[0], model[3] - model[0] ); // compute pseudo inverse matrix modelPseudoInverse = modelVectors.PseudoInverse( ); }
public ConvexResult(Vector3[] hvertices, int[] hindices) { mHullVertices = (Vector3[])hvertices.Clone(); mHullIndices = (int[])hindices.Clone(); }
/// <summary> /// Load /// </summary> /// <param name="inputPoints">Input points</param> /// <param name="widthHelpers">Width helpers</param> /// <param name="roadHelpers">Road helpers</param> /// <param name="neutralObjects">Neutral objects</param> /// <param name="landscape">Landscape</param> protected void Load(Vector3[] inputPoints, List<TrackData.WidthHelper> widthHelpers, List<TrackData.RoadHelper> roadHelpers, List<TrackData.NeutralObject> neutralObjects, Landscape landscape) { #region Kill all previously loaded data points.Clear(); helperPositions.Clear(); // Kill all loaded objects if (landscape != null) landscape.KillAllLoadedObjects(); #endregion #region Make sure we got valid data if (inputPoints == null || inputPoints.Length < 3) throw new ArgumentException("inputPoints is invalid, we need at "+ "least 3 valid input points to generate a TrackLine."); #endregion #region Check if all points are ABOVE the landscape if (landscape != null) { // Go through all spline points for (int num = 0; num < inputPoints.Length; num++) { // Get landscape height here float landscapeHeight = landscape.GetMapHeight( inputPoints[num].X, inputPoints[num].Y) + // add little to fix ground errors MinimumLandscapeDistance * 2.25f; // And make sure we are always above it! if (inputPoints[num].Z < landscapeHeight) inputPoints[num].Z = landscapeHeight; } // for (num) // Second pass, check 24 interpolation points between all inputPoints for (int num = 0; num < inputPoints.Length; num++) for (int iter = 1; iter < 25; iter++) { float iterPercent = iter / 25.0f; float iterHeight = inputPoints[num].Z * (1 - iterPercent) + inputPoints[(num + 1) % inputPoints.Length].Z * iterPercent; // Check 2x2 points (in all directions) to make sure // we don't go through the landscape at the sides for (int x = 0; x < 2; x++) for (int y = 0; y < 2; y++) { // Also get height at middle to next pos float landscapeHeight = landscape.GetMapHeight( -5.0f + 10.0f * x + inputPoints[num].X * (1 - iterPercent) + inputPoints[(num + 1) % inputPoints.Length].X * iterPercent, -5.0f + 10.0f * y + inputPoints[num].Y * (1 - iterPercent) + inputPoints[(num + 1) % inputPoints.Length].Y * iterPercent)+ // add little to fix ground errors MinimumLandscapeDistance * 1.6f;// 1.5f;//1.25f; // Increase both positions if this point is under the landscape if (iterHeight < landscapeHeight) { float increaseHeight = landscapeHeight - iterHeight; inputPoints[num].Z += increaseHeight; inputPoints[(num + 1) % inputPoints.Length].Z += increaseHeight; } // if (iterHeight) } // for } // for for (iter) } // if (landscape) //Log.Write("Input points: " + StringHelper.WriteArrayData(inputPoints)); #endregion #region Search for any loopings indicated by 2 points above each other // Go through all spline points (ignore first and last 3, this // makes it easier to remove points and add new ones). for (int num = 1; num < inputPoints.Length-3; num++) { // X/Y distance has to be 4 times smaller than Z distance Vector3 distVec = inputPoints[num + 1] - inputPoints[num]; float xyDist = (float)Math.Sqrt( distVec.X*distVec.X+distVec.Y*distVec.Y); float zDist = Math.Abs(distVec.Z); // Also check if next point is down again. Vector3 distVec2 = inputPoints[num + 2] - inputPoints[num + 1]; if (zDist / 2 > xyDist && Math.Abs(distVec.Z + distVec2.Z) < zDist / 2) { // Find out which direction we are going Vector3 dir = inputPoints[num] - inputPoints[num - 1]; dir.Normalize(); Vector3 upVec = new Vector3(0, 0, 1); Vector3 rightVec = Vector3.Cross(dir, upVec); // Matrix build helper matrix to rotate our looping points Matrix rotMatrix = new Matrix( rightVec.X, rightVec.Y, rightVec.Z, 0, dir.X, dir.Y, dir.Z, 0, upVec.X, upVec.Y, upVec.Z, 0, 0, 0, 0, 1); // Ok do a looping with zDist as height. // Start with the current point, loop around and end with the // point after the looping. We will remove the current and the // next 2 points, but add 9 new points instead for our smooth loop. // See LoopingPoints for the looping itself. Vector3 startLoopPos = inputPoints[num]; Vector3 endLoopPos = inputPoints[num + 2]; // Insert 7 new points (9 new points, but we reuse // start, middle and end points which are num, num+1 and num+2, // plus an additional point after the looping to keep the road // straight!) Vector3[] remInputPoints = (Vector3[])inputPoints.Clone(); inputPoints = new Vector3[inputPoints.Length + 7]; // Copy everything over for (int copyNum = 0; copyNum < remInputPoints.Length; copyNum++) if (copyNum < num) inputPoints[copyNum] = remInputPoints[copyNum]; else inputPoints[copyNum + 7] = remInputPoints[copyNum]; // Ok, now we can add our loop for (int loopNum = 0; loopNum < LoopingPoints.Length; loopNum++) { // Interpolate between start and end pos to land at the end pos! float loopPercent = loopNum / (float)(LoopingPoints.Length - 1); inputPoints[num + loopNum] = startLoopPos * (1 - loopPercent) + endLoopPos * loopPercent + zDist * Vector3.Transform(LoopingPoints[loopNum], rotMatrix); } // for (loopNum) // Add extra point to keep the road straight Vector3 newRoadDir = inputPoints[num + 10] - inputPoints[num + 8]; // Don't go more than zDist * 2 units away! if (newRoadDir.Length() > zDist * 2) { newRoadDir.Normalize(); newRoadDir = newRoadDir * zDist; inputPoints[num + 9] = inputPoints[num + 8] + newRoadDir; } // if (newRoadDir.Length) else // Just add an interpolation point inputPoints[num + 9] = (inputPoints[num + 8] + inputPoints[num + 10])/2.0f; // Advance 10 points until we check for the next loop num += 10; // That's it, good work everyone ^^ } // if (zDist) } // for (num) #endregion #region Generate all points with help of catmull rom splines // Generate all points with help of catmull rom splines for (int num = 0; num < inputPoints.Length; num++) { // Get the 4 required points for the catmull rom spline Vector3 p1 = inputPoints[num-1 < 0 ? inputPoints.Length-1 : num-1]; Vector3 p2 = inputPoints[num]; Vector3 p3 = inputPoints[(num + 1) % inputPoints.Length]; Vector3 p4 = inputPoints[(num + 2) % inputPoints.Length]; // Calculate number of iterations we use here based // on the distance of the 2 points we generate new points from. float distance = Vector3.Distance(p2, p3); int numberOfIterations = (int)(NumberOfIterationsPer100Meters * (distance / 100.0f)); if (numberOfIterations <= 0) numberOfIterations = 1; Vector3 lastPos = p1; for (int iter = 0; iter < numberOfIterations; iter++) { TrackVertex newVertex = new TrackVertex( Vector3.CatmullRom(p1, p2, p3, p4, iter / (float)numberOfIterations)); lastPos = newVertex.pos; points.Add(newVertex); } // for (iter) } // for (num) #endregion #region Generate up vectors, very important for our road building // Pre up vectors are used to first generate all optimal up vectors // for the track, but this is not useful for driving because we need // the road to point up always except for loopings. List<Vector3> preUpVectors = new List<Vector3>(); // Now generate all up vectors, first pass does optimal up vectors. Vector3 defaultUpVec = new Vector3(0, 0, 1); Vector3 lastUpVec = defaultUpVec; for (int num = 0; num < points.Count; num++) { // Get direction we are driving in at this point, // interpolate with help of last and next points. Vector3 dir = points[(num + 1) % points.Count].pos - points[num - 1 < 0 ? points.Count - 1 : num - 1].pos; dir.Normalize(); // Now calculate the optimal up vector for this point Vector3 middlePoint = (points[(num + 1) % points.Count].pos + points[num - 1 < 0 ? points.Count - 1 : num - 1].pos) / 2.0f; Vector3 optimalUpVector = middlePoint - points[num].pos; if (optimalUpVector.Length() < 0.0001f) optimalUpVector = lastUpVec; optimalUpVector.Normalize(); // Store the optimalUpVectors in the preUpVectors list preUpVectors.Add(optimalUpVector); // Also save dir vector points[num].dir = dir; // And remember the last upVec in case the road is going straight ahead lastUpVec = optimalUpVector; } // for (num) // Interpolate the first up vector for a smoother road at the start pos preUpVectors[0] = preUpVectors[preUpVectors.Count - 1] + preUpVectors[1]; preUpVectors[0].Normalize(); #endregion #region Interpolate the up vectors and also add the dir and right vectors // Second pass, interpolated precalced values and apply our logic :) //preUpVectors[0] = lastUpVec = Vector3.Lerp(defaultUpVec, preUpVectors[0], 1.5f * CurveFactor * UpFactorCorrector); //lastUpVec = preUpVectors[0]; Vector3 lastUpVecUnmodified = lastUpVec;// defaultUpVec; Vector3 lastRightVec = Vector3.Zero; for (int num = 0; num < points.Count; num++) { // Grab dir vector (could be calculated here too) Vector3 dir = points[num].dir; // First of all interpolate the preUpVectors Vector3 upVec = //single input: preUpVectors[num]; Vector3.Zero; for (int smoothNum = -NumberOfUpSmoothValues / 2; smoothNum <= NumberOfUpSmoothValues / 2; smoothNum++) upVec += preUpVectors[(num + points.Count + smoothNum) % points.Count]; upVec.Normalize(); // Find out if this road piece is upside down and if we are // moving up or down. This is VERY important for catching loopings. bool upsideDown = upVec.Z < -0.25f && lastUpVecUnmodified.Z < -0.05f; bool movingUp = dir.Z > 0.75f; bool movingDown = dir.Z < -0.75f; //float changeAngle2 = // GetAngleBetweenVectors(lastUpVec, upVec); //if (num < 100) // Log.Write("changeAngel2=" + changeAngle2); // Mix in the last vector to make curves weaker upVec = Vector3.Lerp(lastUpVec, upVec, CurveFactor); upVec.Normalize(); // Store the last value to check for loopings. lastUpVecUnmodified = upVec; // Don't mix in default up if we head up or are upside down! // Its very useful to know if we move up or down to fix the // problematic areas at loopings by pointing stuff correct right away. if (movingUp) lastUpVec = Vector3.Lerp(upVec, -defaultUpVec, UpFactorCorrector); else if (movingDown) lastUpVec = Vector3.Lerp(upVec, defaultUpVec, UpFactorCorrector); else if (upsideDown) lastUpVec = Vector3.Lerp(upVec, -defaultUpVec, UpFactorCorrector); else lastUpVec = Vector3.Lerp(upVec, defaultUpVec, UpFactorCorrector); // If we are very close to the ground, make the road point up more! if (//upsideDown == false && landscape != null) { // Get landscape height here float landscapeHeight = landscape.GetMapHeight( points[num].pos.X, points[num].pos.Y); // If point is close to the landscape, let everything point up more if (points[num].pos.Z - landscapeHeight < MinimumLandscapeDistance * 4) lastUpVec = Vector3.Lerp(upVec, defaultUpVec, 1.75f * UpFactorCorrector); } // if (upsideDown == false &&) // And finally calculate rightVectors with just a cross product. // Used to render the track later. Vector3 rightVec = Vector3.Cross(dir, upVec); rightVec.Normalize(); points[num].right = rightVec; //*tst // Recalculate up vector with help of right and dir. // This makes the up vector to always point up 90 degrees. upVec = Vector3.Cross(rightVec, dir); upVec.Normalize(); points[num].up = upVec; //*/ //// Make sure we never rotate the road more than a few degrees //if (lastRightVec.Length() > 0) //{ // float changeAngle = // GetAngleBetweenVectors(lastRightVec, rightVec); // if (num < 100) // Log.Write("changeAngel=" + changeAngle); //} // if (lastRightVec.Length) //// Remember right vec for comparison in the next frame. //lastRightVec = rightVec; } // for (num) #endregion #region Smooth up vectors! lastUpVec = points[0].up; for (int num = 0; num < points.Count; num++) preUpVectors[num] = points[num].up; for (int num = 0; num < points.Count; num++) { // Interpolate up vectors again Vector3 upVec = Vector3.Zero; for (int smoothNum = -NumberOfUpSmoothValues; smoothNum <= NumberOfUpSmoothValues; smoothNum++) { upVec += preUpVectors[(num + points.Count + smoothNum) % points.Count]; } // for (smoothNum) upVec.Normalize(); points[num].up = upVec; // Also rebuild right vector Vector3 dir = points[num].dir; points[num].right = Vector3.Cross(dir, upVec); /*suxx // Grab dir and up vector Vector3 dir = points[num].dir; Vector3 upVec = points[num].up; /*suxx // Compare with previous up vector float changeAngle = GetAngleBetweenVectors(lastUpVec, upVec); /*tst bool upsideDown = upVec.Z < -0.25f && lastUpVecUnmodified.Z < -0.05f; bool movingUp = dir.Z > 0.75f; bool movingDown = dir.Z < -0.75f; lastUpVecUnmodified = upVec; if (Math.Abs(changeAngle) > 0.02f && upsideDown == false && movingUp == false && movingDown == false) { points[num].up = Vector3.SmoothStep(lastUpVec, upVec, 0.33f);//.25f); // Also rebuild right vector points[num].right = Vector3.Cross(dir, points[num].up); } // if (Math.Abs) */ /*suxx //if (Math.Abs(changeAngle) > 0.02f) { points[num].up = Vector3.SmoothStep(lastUpVec, upVec, 0.05f);//.25f); // Also rebuild right vector points[num].right = Vector3.Cross(dir, points[num].up); } // if (Math.Abs) lastUpVec = upVec; */ //if (num < 100) // Log.Write("changeAngel=" + changeAngle); } // for (num) #endregion AdjustRoadWidths(widthHelpers); GenerateUTextureCoordinates(); GenerateTunnelsAndLandscapeObjects( roadHelpers, neutralObjects, landscape); }
private Vector3[] getRightLinePoints(Vector3[] points) { Vector3[] secondPoints = (Vector3[])points.Clone(); for(int i = 0; i < secondPoints.Length; i++) { secondPoints[i].x = secondPoints[i].x + getHorizontalCollisionDistance(); } return secondPoints; }