public VerticalGauge(int id, Texture2D skin, Texture2D scale, bool damped = true, float dampfactor = 0.002f) : base(id) { this.damper = new Damper(dampfactor); this.damper.SetEnabled(damped); this.scale = scale; this.skin = skin; this.gaugeBounds = new Rect(0, 0, NanoGauges.configuration.verticalGaugeWidth, NanoGauges.configuration.verticalGaugeHeight); // this.zoom = new VerticalGaugeZoom(this, skin, scale); // this.position.x = 0; this.position.width = 1.0f; if (scale == null) { Log.Error("no scale for gauge " + id + " defined"); } if (skin == null) { Log.Error("no skin for gauge " + id + " defined"); } offFlag = new PowerOffFlag(this); limitFlag = new LimiterFlag(this); }
/// <summary>Callback to to the camera confining</summary> protected override void PostPipelineStageCallback( CinemachineVirtualCameraBase vcam, CinemachineCore.Stage stage, ref CameraState state, float deltaTime) { if (IsValid && stage == CinemachineCore.Stage.Body) { var extra = GetExtraState <VcamExtraState>(vcam); Vector3 displacement; if (m_ConfineScreenEdges && state.Lens.Orthographic) { displacement = ConfineScreenEdges(vcam, ref state); } else { displacement = ConfinePoint(state.CorrectedPosition); } if (m_Damping > 0 && deltaTime >= 0 && VirtualCamera.PreviousStateIsValid) { Vector3 delta = displacement - extra.m_previousDisplacement; delta = Damper.Damp(delta, m_Damping, deltaTime); displacement = extra.m_previousDisplacement + delta; } extra.m_previousDisplacement = displacement; state.PositionCorrection += displacement; extra.confinerDisplacement = displacement.magnitude; } }
public override void MutateCameraState(ref CameraState curState, float deltaTime) { CinemachineTargetGroup targetGroup = this.TargetGroup; if (targetGroup == null) { base.MutateCameraState(ref curState, deltaTime); return; } if (!this.IsValid || !curState.HasLookAt) { this.m_prevTargetHeight = 0f; return; } curState.ReferenceLookAt = this.GetLookAtPointAndSetTrackedPoint(targetGroup.transform.position); Vector3 v = base.TrackedPoint - curState.RawPosition; float magnitude = v.magnitude; if (magnitude < 0.0001f) { return; } Vector3 vector = v.AlmostZero() ? Vector3.forward : v.normalized; Bounds boundingBox = targetGroup.BoundingBox; this.m_lastBoundsMatrix = Matrix4x4.TRS(boundingBox.center - vector * boundingBox.extents.magnitude, Quaternion.LookRotation(vector, curState.ReferenceUp), Vector3.one); this.m_LastBounds = targetGroup.GetViewSpaceBoundingBox(this.m_lastBoundsMatrix); float num = this.GetTargetHeight(this.m_LastBounds); Vector3 a = this.m_lastBoundsMatrix.MultiplyPoint3x4(this.m_LastBounds.center); if (deltaTime >= 0f) { float num2 = num - this.m_prevTargetHeight; num2 = Damper.Damp(num2, this.m_FrameDamping, deltaTime); num = this.m_prevTargetHeight + num2; } this.m_prevTargetHeight = num; if (!curState.Lens.Orthographic && this.m_AdjustmentMode != CinemachineGroupComposer.AdjustmentMode.ZoomOnly) { float fieldOfView = curState.Lens.FieldOfView; float num3 = num / (2f * Mathf.Tan(fieldOfView * 0.0174532924f / 2f)) + this.m_LastBounds.extents.z; num3 = Mathf.Clamp(num3, magnitude - this.m_MaxDollyIn, magnitude + this.m_MaxDollyOut); num3 = Mathf.Clamp(num3, this.m_MinimumDistance, this.m_MaximumDistance); curState.PositionCorrection += a - vector * num3 - curState.RawPosition; } if (curState.Lens.Orthographic || this.m_AdjustmentMode != CinemachineGroupComposer.AdjustmentMode.DollyOnly) { float num4 = (base.TrackedPoint - curState.CorrectedPosition).magnitude - this.m_LastBounds.extents.z; float value = 179f; if (num4 > 0.0001f) { value = 2f * Mathf.Atan(num / (2f * num4)) * 57.29578f; } LensSettings lens = curState.Lens; lens.FieldOfView = Mathf.Clamp(value, this.m_MinimumFOV, this.m_MaximumFOV); lens.OrthographicSize = Mathf.Clamp(num / 2f, this.m_MinimumOrthoSize, this.m_MaximumOrthoSize); curState.Lens = lens; } base.MutateCameraState(ref curState, deltaTime); }
protected override void PostPipelineStageCallback(CinemachineVirtualCameraBase vcam, CinemachineCore.Stage stage, ref CameraState state, float deltaTime) { CinemachineCollider.VcamExtraState vcamExtraState = null; if (stage == CinemachineCore.Stage.Body) { vcamExtraState = base.GetExtraState <CinemachineCollider.VcamExtraState>(vcam); vcamExtraState.targetObscured = false; vcamExtraState.colliderDisplacement = 0f; vcamExtraState.debugResolutionPath = null; } if (stage == CinemachineCore.Stage.Body && this.m_AvoidObstacles) { Vector3 vector = this.PreserveLignOfSight(ref state, ref vcamExtraState); if (this.m_Damping > 0f && deltaTime >= 0f) { Vector3 vector2 = vector - vcamExtraState.m_previousDisplacement; vector2 = Damper.Damp(vector2, this.m_Damping, deltaTime); vector = vcamExtraState.m_previousDisplacement + vector2; } vcamExtraState.m_previousDisplacement = vector; state.PositionCorrection += vector; vcamExtraState.colliderDisplacement += vector.magnitude; } if (stage == CinemachineCore.Stage.Aim) { vcamExtraState = base.GetExtraState <CinemachineCollider.VcamExtraState>(vcam); vcamExtraState.targetObscured = this.CheckForTargetObstructions(state); if (vcamExtraState.targetObscured) { state.ShotQuality *= 0.2f; } if (vcamExtraState.colliderDisplacement > 0f) { state.ShotQuality *= 0.8f; } float num = 0f; if (this.m_OptimalTargetDistance > 0f && state.HasLookAt) { float num2 = Vector3.Magnitude(state.ReferenceLookAt - state.FinalPosition); if (num2 <= this.m_OptimalTargetDistance) { float num3 = this.m_OptimalTargetDistance / 2f; if (num2 >= num3) { num = 0.2f * (num2 - num3) / (this.m_OptimalTargetDistance - num3); } } else { num2 -= this.m_OptimalTargetDistance; float num4 = this.m_OptimalTargetDistance * 3f; if (num2 < num4) { num = 0.2f * (1f - num2 / num4); } } state.ShotQuality *= 1f + num; } } }
protected override void PostPipelineStageCallback(CinemachineVirtualCameraBase vcam, CinemachineCore.Stage stage, ref CameraState state, float deltaTime) { if (this.IsValid && stage == CinemachineCore.Stage.Body) { Vector3 vector; if (this.m_ConfineScreenEdges && state.Lens.Orthographic) { vector = this.ConfineScreenEdges(vcam, ref state); } else { vector = this.ConfinePoint(state.CorrectedPosition); } CinemachineConfiner.VcamExtraState extraState = base.GetExtraState <CinemachineConfiner.VcamExtraState>(vcam); if (this.m_Damping > 0f && deltaTime >= 0f) { Vector3 vector2 = vector - extraState.m_previousDisplacement; vector2 = Damper.Damp(vector2, this.m_Damping, deltaTime); vector = extraState.m_previousDisplacement + vector2; } extraState.m_previousDisplacement = vector; state.PositionCorrection += vector; extraState.confinerDisplacement = vector.magnitude; } }
/// <summary> /// Callback to do the camera confining /// </summary> /// <param name="vcam">The virtual camera being processed</param> /// <param name="stage">The current pipeline stage</param> /// <param name="state">The current virtual camera state</param> /// <param name="deltaTime">The current applicable deltaTime</param> protected override void PostPipelineStageCallback( CinemachineVirtualCameraBase vcam, CinemachineCore.Stage stage, ref CameraState state, float deltaTime) { if (stage == CinemachineCore.Stage.Body) { var aspectRatio = state.Lens.Aspect; if (!m_shapeCache.ValidateCache( m_BoundingShape2D, m_MaxWindowSize, aspectRatio, out bool confinerStateChanged)) { return; // invalid path } var oldCameraPos = state.CorrectedPosition; var cameraPosLocal = m_shapeCache.m_DeltaWorldToBaked.MultiplyPoint3x4(oldCameraPos); var currentFrustumHeight = CalculateHalfFrustumHeight(state, cameraPosLocal.z); // convert frustum height from world to baked space. deltaWorldToBaked.lossyScale is always uniform. var bakedSpaceFrustumHeight = currentFrustumHeight * m_shapeCache.m_DeltaWorldToBaked.lossyScale.x; // Make sure we have a solution for our current frustum size var extra = GetExtraState <VcamExtraState>(vcam); extra.m_vcam = vcam; if (confinerStateChanged || extra.m_BakedSolution == null || !extra.m_BakedSolution.IsValid(bakedSpaceFrustumHeight)) { extra.m_BakedSolution = m_shapeCache.m_confinerOven.GetBakedSolution(bakedSpaceFrustumHeight); } cameraPosLocal = extra.m_BakedSolution.ConfinePoint(cameraPosLocal); var newCameraPos = m_shapeCache.m_DeltaBakedToWorld.MultiplyPoint3x4(cameraPosLocal); // Don't move the camera along its z-axis var fwd = state.CorrectedOrientation * Vector3.forward; newCameraPos -= fwd * Vector3.Dot(fwd, newCameraPos - oldCameraPos); // Remember the desired displacement for next frame var prev = extra.m_PreviousDisplacement; var displacement = newCameraPos - oldCameraPos; extra.m_PreviousDisplacement = displacement; if (!VirtualCamera.PreviousStateIsValid || deltaTime < 0 || m_Damping <= 0) { extra.m_DampedDisplacement = Vector3.zero; } else { // If a big change from previous frame's desired displacement is detected, // assume we are going around a corner and extract that difference for damping if (prev.sqrMagnitude > 0.01f && Vector2.Angle(prev, displacement) > k_cornerAngleTreshold) { extra.m_DampedDisplacement += displacement - prev; } extra.m_DampedDisplacement -= Damper.Damp(extra.m_DampedDisplacement, m_Damping, deltaTime); displacement -= extra.m_DampedDisplacement; } state.PositionCorrection += displacement; } }
public void TwoBodysWithDamperPullTogether() { World w = new World (); Rigid r1 = new Rigid (30, new Matrix (70, 70, 70)); r1.StartCenterOfMass = new Vector (); w.AddRigid (r1); w.AddEffect (new Force (new Vector (30, 0, 0), r1)); Rigid r2 = new Rigid (30, new Matrix (70, 70, 70)); r2.StartCenterOfMass = new Vector (10, 0, 0); w.AddRigid (r2); w.AddEffect (new Force (new Vector (-30, 0, 0), r2)); Vector v = new Vector (); Damper damper = new Damper (r1, v, r2, v, 30); w.AddEffect (damper); State s1 = new State (w); s1.Simulate (5); Assert.AreEqual (2.25, s1.RigidStates [r1].CenterOfMass.X, 0.001); Assert.AreEqual (0.5, s1.RigidStates [r1].LinearVelocity.X, 0.001); Assert.AreEqual (0.0, s1.RigidStates [r1].LinearAcceleration.X, 0.001); Assert.AreEqual (7.75, s1.RigidStates [r2].CenterOfMass.X, 0.001); Assert.AreEqual (-0.5, s1.RigidStates [r2].LinearVelocity.X, 0.001); Assert.AreEqual (0.0, s1.RigidStates [r2].LinearAcceleration.X, 0.001); }
private void SolveButton_Click(object sender, EventArgs e) { Particle Earth = new Particle(new Mass(5.97237E24)); Particle particle = new Particle(new Mass(Convert.ToDouble(massBox.Text))); Spring spring = new Spring(particle, Earth, Convert.ToDouble(springRateBox.Text)); Damper damper = new Damper(spring, Convert.ToDouble(dampingRatioBox.Text)); Time lengthOfSimulation = new Time(Convert.ToDouble(timeBox.Text)); particle.interactions.Add(spring); particle.interactions.Add(damper); particle.position.values[0] = 1.0; PhysicalSystem system = new PhysicalSystem(new List <Particle>() { particle, Earth }); int numberOfPoints = 1024; Time timeStep = lengthOfSimulation / numberOfPoints; chart1.ChartAreas["ChartArea"].AxisX.Maximum = lengthOfSimulation.value; for (Time time = new Time(); time <= lengthOfSimulation; time += timeStep) { chart1.Series["Series"].Points.AddXY(time.value, particle.position.values[0]); system.Iterate(timeStep); } this.Refresh(); }
protected override void PostPipelineStageCallback(CinemachineVirtualCameraBase vcam, CinemachineCore.Stage stage, ref CameraState state, float deltaTime) { CinemachineFollowZoom.VcamExtraState extraState = base.GetExtraState <CinemachineFollowZoom.VcamExtraState>(vcam); if (!base.enabled || deltaTime < 0f) { extraState.m_previousFrameZoom = state.Lens.FieldOfView; } if (stage == CinemachineCore.Stage.Body) { float num = Mathf.Max(this.m_Width, 0f); float value = 179f; float num2 = Vector3.Distance(state.CorrectedPosition, state.ReferenceLookAt); if (num2 > 0.0001f) { float min = num2 * 2f * Mathf.Tan(this.m_MinFOV * 0.0174532924f / 2f); float max = num2 * 2f * Mathf.Tan(this.m_MaxFOV * 0.0174532924f / 2f); num = Mathf.Clamp(num, min, max); if (deltaTime >= 0f && this.m_Damping > 0f) { float num3 = num2 * 2f * Mathf.Tan(extraState.m_previousFrameZoom * 0.0174532924f / 2f); float num4 = num - num3; num4 = Damper.Damp(num4, this.m_Damping, deltaTime); num = num3 + num4; } value = 2f * Mathf.Atan(num / (2f * num2)) * 57.29578f; } LensSettings lens = state.Lens; lens.FieldOfView = (extraState.m_previousFrameZoom = Mathf.Clamp(value, this.m_MinFOV, this.m_MaxFOV)); state.Lens = lens; } }
private Vector3 OrthoOffsetToScreenBounds( Vector3 targetPos2D, Rect screenRect, float deltaTime, out bool moved) { // Bring it to the edge of screenRect, if outside. Leave it alone if inside. Vector3 delta = Vector3.zero; if (targetPos2D.x < screenRect.xMin) { delta.x += targetPos2D.x - screenRect.xMin; } if (targetPos2D.x > screenRect.xMax) { delta.x += targetPos2D.x - screenRect.xMax; } if (targetPos2D.y < screenRect.yMin) { delta.y += targetPos2D.y - screenRect.yMin; } if (targetPos2D.y > screenRect.yMax) { delta.y += targetPos2D.y - screenRect.yMax; } // Apply damping if (deltaTime >= 0) { delta.x = Damper.Damp(delta.x, m_XDamping, deltaTime); delta.y = Damper.Damp(delta.y, m_YDamping, deltaTime); } moved = Mathf.Abs(delta.x) > 0 || Mathf.Abs(delta.y) > 0; return(delta); }
/// <summary> /// Get the value of the tenvelope at a given time relative to the envelope start. /// </summary> /// <param name="offset">Time in seconds from the envelope start</param> /// <returns>Envelope amplitude. This will range from 0...1</returns> public float GetValueAt(float offset) { if (offset >= 0) { if (offset < m_AttackTime && m_AttackTime > Epsilon) { if (m_AttackShape == null || m_AttackShape.length < 2) { return(Damper.Damp(1, m_AttackTime, offset)); } return(m_AttackShape.Evaluate(offset / m_AttackTime)); } offset -= m_AttackTime; if (m_HoldForever || offset < m_SustainTime) { return(1); } offset -= m_SustainTime; if (offset < m_DecayTime && m_DecayTime > Epsilon) { if (m_DecayShape == null || m_DecayShape.length < 2) { return(1 - Damper.Damp(1, m_DecayTime, offset)); } return(m_DecayShape.Evaluate(offset / m_DecayTime)); } } return(0); }
protected override void PostPipelineStageCallback( CinemachineVirtualCameraBase vcam, CinemachineCore.Stage stage, ref CameraState state, float deltaTime) { if (stage == CinemachineCore.Stage.Body) { _framingTransposer = ((CinemachineVirtualCamera)vcam).GetCinemachineComponent <CinemachineFramingTransposer>(); if (_framingTransposer == null) { return; } float d = Vector3.Distance(state.CorrectedPosition, state.ReferenceLookAt); float _distance = m_CameraDistance; // Apply damping if (deltaTime >= 0 && m_Damping > 0) { float delta = m_CameraDistance - d; delta = Damper.Damp(delta, m_Damping, deltaTime); _distance = d + delta; } _framingTransposer.m_CameraDistance = _distance; } }
/// <summary>Calculate the the decay applicable at a given distance from the impact point</summary> /// <returns>Scale factor 0...1</returns> public float DistanceDecay(float distance) { float radius = Mathf.Max(m_Radius, 0); if (distance < radius) { return(1); } distance -= radius; if (distance >= m_DissipationDistance) { return(0); } switch (m_DissipationMode) { default: case DissipationMode.LinearDecay: return(Mathf.Lerp(1, 0, distance / m_DissipationDistance)); case DissipationMode.SoftDecay: return(0.5f * (1 + Mathf.Cos(Mathf.PI * (distance / m_DissipationDistance)))); case DissipationMode.ExponentialDecay: return(1 - Damper.Damp(1, m_DissipationDistance, distance)); } }
/// <summary>Callback to to the camera confining</summary> protected override void PostPipelineStageCallback( CinemachineVirtualCameraBase vcam, CinemachineCore.Stage stage, ref CameraState state, float deltaTime) { if (m_BoundingVolume != null) { // Move the body before the Aim is calculated if (stage == CinemachineCore.Stage.Body) { Vector3 displacement; if (m_ConfineScreenEdges && state.Lens.Orthographic) { displacement = ConfineScreenEdges(vcam, ref state); } else { displacement = ConfinePoint(state.CorrectedPosition); } VcamExtraState extra = GetExtraState <VcamExtraState>(vcam); if (m_Damping > 0 && deltaTime >= 0) { Vector3 delta = displacement - extra.m_previousDisplacement; delta = Damper.Damp(delta, m_Damping, deltaTime); displacement = extra.m_previousDisplacement + delta; } extra.m_previousDisplacement = displacement; state.PositionCorrection += displacement; extra.confinerDisplacement = displacement.magnitude; } } }
public void Update() { if (!settings.enabled) { return; } var orbit = sourceFreeLook.m_Orbits[1]; if (characterYAxis.GetValue() > 0 && !DCLCharacterController.i.isWalking) { currentDampingDelay += Time.deltaTime; if (currentDampingDelay > settings.inDampingDelay) { orbit.m_Radius += Damper.Damp(settings.distanceMax - orbit.m_Radius, settings.inDampingTime, Time.deltaTime); sourceFreeLook.m_Lens.FieldOfView += Damper.Damp(settings.fovMax - sourceFreeLook.m_Lens.FieldOfView, settings.inDampingTime, Time.deltaTime); } } else { currentDampingDelay = 0; orbit.m_Radius += Damper.Damp(settings.distanceMin - orbit.m_Radius, settings.outDampingTime, Time.deltaTime); sourceFreeLook.m_Lens.FieldOfView += Damper.Damp(settings.fovMin - sourceFreeLook.m_Lens.FieldOfView, settings.outDampingTime, Time.deltaTime); } sourceFreeLook.m_Orbits[1] = orbit; }
float AdjustCameraDepthAndLensForGroupFraming( CinemachineTargetGroup group, float targetZ, ref CameraState curState, float deltaTime) { float cameraOffset = 0; // Get the bounding box from that POV in view space, and find its height Bounds bounds = group.BoundingBox; Vector3 fwd = curState.RawOrientation * Vector3.forward; m_lastBoundsMatrix = Matrix4x4.TRS( bounds.center - (fwd * bounds.extents.magnitude), curState.RawOrientation, Vector3.one); m_LastBounds = group.GetViewSpaceBoundingBox(m_lastBoundsMatrix); float targetHeight = GetTargetHeight(m_LastBounds); // Apply damping if (deltaTime >= 0) { float delta = targetHeight - m_prevTargetHeight; delta = Damper.Damp(delta, m_ZDamping, deltaTime); targetHeight = m_prevTargetHeight + delta; } m_prevTargetHeight = targetHeight; // Move the camera if (!curState.Lens.Orthographic && m_AdjustmentMode != AdjustmentMode.ZoomOnly) { // What distance would be needed to get the target height, at the current FOV float desiredDistance = targetHeight / (2f * Mathf.Tan(curState.Lens.FieldOfView * Mathf.Deg2Rad / 2f)); // target the near surface of the bounding box desiredDistance += m_LastBounds.extents.z; // Clamp to respect min/max distance settings desiredDistance = Mathf.Clamp( desiredDistance, targetZ - m_MaxDollyIn, targetZ + m_MaxDollyOut); desiredDistance = Mathf.Clamp(desiredDistance, m_MinimumDistance, m_MaximumDistance); // Apply cameraOffset += desiredDistance - targetZ; } // Apply zoom if (curState.Lens.Orthographic || m_AdjustmentMode != AdjustmentMode.DollyOnly) { float nearBoundsDistance = (targetZ + cameraOffset) - m_LastBounds.extents.z; float currentFOV = 179; if (nearBoundsDistance > Epsilon) currentFOV = 2f * Mathf.Atan(targetHeight / (2 * nearBoundsDistance)) * Mathf.Rad2Deg; LensSettings lens = curState.Lens; lens.FieldOfView = Mathf.Clamp(currentFOV, m_MinimumFOV, m_MaximumFOV); lens.OrthographicSize = Mathf.Clamp(targetHeight / 2, m_MinimumOrthoSize, m_MaximumOrthoSize); curState.Lens = lens; } return -cameraOffset; }
/// <summary> /// Adjust the rigOrientation to put the camera within the screen bounds. /// If deltaTime >= 0 then damping will be applied. /// Assumes that currentOrientation fwd is such that input rigOrientation's /// local up is NEVER NEVER NEVER pointing downwards, relative to /// state.ReferenceUp. If this condition is violated /// then you will see crazy spinning. That's the symptom. /// </summary> private bool RotateToScreenBounds( ref CameraState state, Rect screenRect, ref Quaternion rigOrientation, float fov, float fovH, float deltaTime) { Vector3 targetDir = TrackedPoint - state.CorrectedPosition; Vector2 rotToRect = rigOrientation.GetCameraRotationToTarget(targetDir, state.ReferenceUp); // Bring it to the edge of screenRect, if outside. Leave it alone if inside. ClampVerticalBounds(ref screenRect, targetDir, state.ReferenceUp, fov); float min = (screenRect.yMin - 0.5f) * fov; float max = (screenRect.yMax - 0.5f) * fov; if (rotToRect.x < min) { rotToRect.x -= min; } else if (rotToRect.x > max) { rotToRect.x -= max; } else { rotToRect.x = 0; } min = (screenRect.xMin - 0.5f) * fovH; max = (screenRect.xMax - 0.5f) * fovH; if (rotToRect.y < min) { rotToRect.y -= min; } else if (rotToRect.y > max) { rotToRect.y -= max; } else { rotToRect.y = 0; } // Apply damping if (deltaTime >= 0) { rotToRect.x = Damper.Damp(rotToRect.x, m_VerticalDamping, deltaTime); rotToRect.y = Damper.Damp(rotToRect.y, m_HorizontalDamping, deltaTime); } // Rotate rigOrientation = rigOrientation.ApplyCameraRotation(rotToRect, state.ReferenceUp); #if false // GML this gives false positives when the camera is moving. // The way to address this would be to grow the hard rect by the amount // that it would be damped return(Mathf.Abs(rotToRect.x) > Epsilon || Mathf.Abs(rotToRect.y) > Epsilon); #else return(false); #endif }
// Make the spring dampers in my cloth connecting the particles. void MakeDampers() { for (int i = 0; i < points.Count; i++) { if (i % rowLength != rowLength - 1) { GameObject temp = Instantiate(Damp, new Vector3(0, 0, 0), new Quaternion()) as GameObject; Damper dp = new Damper(); dp.P1 = points[i]; dp.P2 = points[i + 1]; dp.speed = speed; temp.GetComponent <Monodamper>().d = dp; temp.name = i.ToString(); dampers.Add(dp); } if (i < ((rowLength * rowLength) - rowLength)) { GameObject temp = Instantiate(Damp, new Vector3(0, 0, 0), new Quaternion()) as GameObject; Damper dp = new Damper(); dp.P1 = points[i]; dp.P2 = points[i + rowLength]; dp.speed = speed; temp.GetComponent <Monodamper>().d = dp; temp.name = i.ToString(); dampers.Add(dp); } if (i % rowLength != (rowLength - 1) && i < (rowLength * rowLength) - rowLength) { GameObject temp = Instantiate(Damp, new Vector3(0, 0, 0), new Quaternion()) as GameObject; Damper dp = new Damper(); dp.P1 = points[i]; dp.P2 = points[i + (rowLength + 1)]; dp.speed = speed; temp.GetComponent <Monodamper>().d = dp; temp.name = i.ToString(); dampers.Add(dp); } if (i % rowLength != 0 && i < (rowLength * rowLength) - rowLength) { GameObject temp = Instantiate(Damp, new Vector3(0, 0, 0), new Quaternion()) as GameObject; Damper dp = new Damper(); dp.P1 = points[i]; dp.P2 = points[i + (rowLength - 1)]; dp.speed = speed; temp.GetComponent <Monodamper>().d = dp; temp.name = i.ToString(); dampers.Add(dp); } if (/*i == 0 || i == (rowLength - 1) || */ i == ((rowLength * rowLength) - 1) || i == ((rowLength * rowLength) - rowLength)) { points[i].ap = false; } } }
/// <summary>Positions the virtual camera according to the transposer rules.</summary> /// <param name="deltaTime">Used for damping. If less than 0, no damping is done.</param> /// <param name="up">Current camera up</param> /// <param name="desiredCameraOffset">Where we want to put the camera relative to the follow target</param> /// <param name="outTargetPosition">Resulting camera position</param> /// <param name="outTargetOrient">Damped target orientation</param> protected void TrackTarget( float deltaTime, Vector3 up, Vector3 desiredCameraOffset, out Vector3 outTargetPosition, out Quaternion outTargetOrient) { Quaternion targetOrientation = GetReferenceOrientation(up); Quaternion dampedOrientation = targetOrientation; if (deltaTime >= 0) { if (m_AngularDampingMode == AngularDampingMode.Quaternion && m_BindingMode == BindingMode.LockToTarget) { float t = Damper.Damp(1, m_AngularDamping, deltaTime); dampedOrientation = Quaternion.Slerp( m_PreviousReferenceOrientation, targetOrientation, t); } else { Vector3 relative = (Quaternion.Inverse(m_PreviousReferenceOrientation) * targetOrientation).eulerAngles; for (int i = 0; i < 3; ++i) { if (relative[i] > 180) { relative[i] -= 360; } } relative = Damper.Damp(relative, AngularDamping, deltaTime); dampedOrientation = m_PreviousReferenceOrientation * Quaternion.Euler(relative); } } m_PreviousReferenceOrientation = dampedOrientation; Vector3 targetPosition = FollowTargetPosition; Vector3 currentPosition = m_PreviousTargetPosition; Vector3 worldOffset = targetPosition - currentPosition; // Adjust for damping, which is done in camera-offset-local coords if (deltaTime >= 0) { Quaternion dampingSpace; if (desiredCameraOffset.AlmostZero()) { dampingSpace = VcamState.RawOrientation; } else { dampingSpace = Quaternion.LookRotation(dampedOrientation * desiredCameraOffset.normalized, up); } Vector3 localOffset = Quaternion.Inverse(dampingSpace) * worldOffset; localOffset = Damper.Damp(localOffset, Damping, deltaTime); worldOffset = dampingSpace * localOffset; } outTargetPosition = m_PreviousTargetPosition = currentPosition + worldOffset; outTargetOrient = dampedOrientation; }
private void NewDamper() { IVehicleComponent Damper = new Damper(CurrentProject.GetValidName(VehicleComponentType.Damper)); DamperNeedsToAdd = true; CurrentProject.DamperNeedsToAdd = true; AddToTreeList(Damper); CurrentProject.AddDamper(Damper); }
/// <summary> /// the suspension of a single wheel /// </summary> /// <param name="wheel">the wheel for which the suspension is</param> public WheelSuspension(ImportantClasses.Enums.Wheels wheel) { BellCrank = new BellCrank(); Damper = new Damper(); PushRod = new PushRod(); WheelHub = new WheelHub(); Wishbone = new Wishbone(); Wheel = wheel; _actualCalculation = new SuspensionOutput(); }
public bool GetReaction( float deltaTime, Vector3 impulsePos, out Vector3 pos, out Quaternion rot) { if (!m_Initialized) { m_Initialized = true; m_CurrentAmount = 0; m_CurrentDamping = 0; m_CurrentTime = CinemachineCore.CurrentTime * m_FrequencyGain; if (m_NoiseOffsets == Vector3.zero) { ReSeed(); } } // Is there any reacting to do? pos = Vector3.zero; rot = Quaternion.identity; var sqrMag = impulsePos.sqrMagnitude; if (m_SecondaryNoise == null || (sqrMag < 0.001f && m_CurrentAmount < 0.0001f)) { return(false); } // Advance the current reaction time if (TargetPositionCache.CacheMode == TargetPositionCache.Mode.Playback && TargetPositionCache.HasCurrentTime) { m_CurrentTime = TargetPositionCache.CurrentTime * m_FrequencyGain; } else { m_CurrentTime += deltaTime * m_FrequencyGain; } // Adjust the envelope height and duration of the secondary noise, // acording to the strength of the incoming signal m_CurrentAmount = Mathf.Max(m_CurrentAmount, Mathf.Sqrt(sqrMag)); m_CurrentDamping = Mathf.Max(m_CurrentDamping, Mathf.Max(1, Mathf.Sqrt(m_CurrentAmount)) * m_Duration); var gain = m_CurrentAmount * m_AmplitudeGain; pos = NoiseSettings.GetCombinedFilterResults( m_SecondaryNoise.PositionNoise, m_CurrentTime, m_NoiseOffsets) * gain; rot = Quaternion.Euler(NoiseSettings.GetCombinedFilterResults( m_SecondaryNoise.OrientationNoise, m_CurrentTime, m_NoiseOffsets) * gain); m_CurrentAmount -= Damper.Damp(m_CurrentAmount, m_CurrentDamping, deltaTime); m_CurrentDamping -= Damper.Damp(m_CurrentDamping, m_CurrentDamping, deltaTime); return(true); }
public override void OnStart(StartState state) { base.OnStart(state); if (!string.IsNullOrEmpty(Sensor)) { var sensor = part.FindModelComponent <MeshFilter>(Sensor); if (sensor != null) { sensor.AddCollider(true); damper = sensor.gameObject.AddComponent <Damper>(); damper.Init(part, Attenuation, MagnetLocation, AffectedPartTags); } } }
/// <summary> /// Adjust the rigOrientation to put the camera within the screen bounds. /// If deltaTime >= 0 then damping will be applied. /// Assumes that currentOrientation fwd is such that input rigOrientation's /// local up is NEVER NEVER NEVER pointing downwards, relative to /// state.ReferenceUp. If this condition is violated /// then you will see crazy spinning. That's the symptom. /// </summary> private void RotateToScreenBounds( ref CameraState state, Rect screenRect, Vector3 trackedPoint, ref Quaternion rigOrientation, float fov, float fovH, float deltaTime) { Vector3 targetDir = trackedPoint - state.CorrectedPosition; Vector2 rotToRect = rigOrientation.GetCameraRotationToTarget(targetDir, state.ReferenceUp); // Bring it to the edge of screenRect, if outside. Leave it alone if inside. ClampVerticalBounds(ref screenRect, targetDir, state.ReferenceUp, fov); float min = (screenRect.yMin - 0.5f) * fov; float max = (screenRect.yMax - 0.5f) * fov; if (rotToRect.x < min) { rotToRect.x -= min; } else if (rotToRect.x > max) { rotToRect.x -= max; } else { rotToRect.x = 0; } min = (screenRect.xMin - 0.5f) * fovH; max = (screenRect.xMax - 0.5f) * fovH; if (rotToRect.y < min) { rotToRect.y -= min; } else if (rotToRect.y > max) { rotToRect.y -= max; } else { rotToRect.y = 0; } // Apply damping if (deltaTime >= 0) { rotToRect.x = Damper.Damp(rotToRect.x, m_VerticalDamping, deltaTime); rotToRect.y = Damper.Damp(rotToRect.y, m_HorizontalDamping, deltaTime); } // Rotate rigOrientation = rigOrientation.ApplyCameraRotation(rotToRect, state.ReferenceUp); }
/// <summary> /// Updates the state of this axis based on the axis defined /// by AxisState.m_AxisName /// </summary> /// <param name="deltaTime">Delta time in seconds</param> /// <returns>Returns <b>true</b> if this axis' input was non-zero this Update, /// <b>false</b> otherwise</returns> public bool Update(float deltaTime) { if (!string.IsNullOrEmpty(m_InputAxisName)) { try { m_InputAxisValue = CinemachineCore.GetInputAxis(m_InputAxisName); } catch (ArgumentException e) { Debug.LogError(e.ToString()); } } float input = m_InputAxisValue; if (m_InvertInput) { input *= -1f; } if (m_SpeedMode == SpeedMode.MaxSpeed) { return(MaxSpeedUpdate(input, deltaTime)); // legacy mode } // Direct mode update: maxSpeed interpreted as multiplier input *= m_MaxSpeed; if (deltaTime < Epsilon) { mCurrentSpeed = 0; } else { float speed = input / deltaTime; float dampTime = Mathf.Abs(speed) < Mathf.Abs(mCurrentSpeed) ? m_DecelTime : m_AccelTime; speed = mCurrentSpeed + Damper.Damp(speed - mCurrentSpeed, dampTime, deltaTime); mCurrentSpeed = speed; // Decelerate to the end points of the range if not wrapping float range = m_MaxValue - m_MinValue; if (!m_Wrap && m_DecelTime > Epsilon && range > Epsilon) { float v0 = ClampValue(Value); float v = ClampValue(v0 + speed * deltaTime); float d = (speed > 0) ? m_MaxValue - v : v - m_MinValue; if (d < (0.1f * range) && Mathf.Abs(speed) > Epsilon) { speed = Damper.Damp(v - v0, m_DecelTime, deltaTime) / deltaTime; } } input = speed * deltaTime; } Value = ClampValue(Value + input); return(Mathf.Abs(input) > Epsilon); }
public bool Update(float deltaTime, ref AxisState axis) { if (!string.IsNullOrEmpty(name)) { try { inputValue = CinemachineCore.GetInputAxis(name); } catch (ArgumentException) { } } //catch (ArgumentException e) { Debug.LogError(e.ToString()); } var inverted = isInverted ? -1 : 1; var input = inputValue * sensitivity * multiplier * inverted; if (deltaTime < Epsilon) { mCurrentSpeed = 0; } else { var speed = input / deltaTime; var dampTime = Mathf.Abs(speed) < Mathf.Abs(mCurrentSpeed) ? decelerationTime : accelerationTime; speed = mCurrentSpeed + Damper.Damp(speed - mCurrentSpeed, dampTime, deltaTime); mCurrentSpeed = speed; // Decelerate to the end points of the range if not wrapping var range = axis.m_MaxValue - axis.m_MinValue; if (!axis.m_Wrap && decelerationTime > Epsilon && range > Epsilon) { var v0 = ClampValue(ref axis, axis.Value); var v = ClampValue(ref axis, v0 + speed * deltaTime); var d = speed > 0 ? axis.m_MaxValue - v : v - axis.m_MinValue; if (d < 0.1f * range && Mathf.Abs(speed) > Epsilon) { speed = Damper.Damp(v - v0, decelerationTime, deltaTime) / deltaTime; } } input = speed * deltaTime; } axis.Value = ClampValue(ref axis, axis.Value + input); return(Mathf.Abs(inputValue) > Epsilon); }
/// <summary>Applies the composer rules and orients the camera accordingly</summary> /// <param name="curState">The current camera state</param> /// <param name="deltaTime">Used for calculating damping. If less than /// zero, then target will snap to the center of the dead zone.</param> public override void MutateCameraState(ref CameraState curState, float deltaTime) { if (!IsValid) { return; } Vector3 dampedPos = FollowTargetPosition; if (deltaTime >= 0) { dampedPos = m_PreviousTargetPosition + Damper.Damp( dampedPos - m_PreviousTargetPosition, m_Damping, deltaTime); } m_PreviousTargetPosition = dampedPos; curState.RawPosition = dampedPos; }
public void InitIfNull() { // Objects if (wheel == null) { wheel = new Wheel(); } if (hit == null) { hit = new WheelHit(); } if (spring == null) { spring = new Spring(); } if (damper == null) { damper = new Damper(); } if (fFriction == null) { fFriction = new Friction(); } if (sFriction == null) { sFriction = new Friction(); } // Curves if (springCurve == null) { springCurve = GenerateDefaultSpringCurve(); } if (damperCurve == null) { damperCurve = GenerateDefaultDamperCurve(); } if (sideFriction.frictionCurve == null) { sideFriction.frictionCurve = SetFrictionParams(sideFriction, new Vector4(10.0f, 1.9f, 1.0f, 0.97f)); } if (forwardFriction.frictionCurve == null) { forwardFriction.frictionCurve = SetFrictionParams(forwardFriction, new Vector4(10.0f, 1.9f, 1.0f, 0.97f)); } }
void PositionCamera(ref CameraState curState, float deltaTime) { var targetPos = FollowTargetPosition; var prevTargetPos = deltaTime >= 0 ? PreviousFollowTargetPosition : targetPos; // Compute damped target pos (compute in camera space) var dampedTargetPos = Quaternion.Inverse(curState.RawOrientation) * (targetPos - prevTargetPos); if (deltaTime >= 0) dampedTargetPos = Damper.Damp(dampedTargetPos, Damping, deltaTime); dampedTargetPos = prevTargetPos + curState.RawOrientation * dampedTargetPos; // Get target rotation (worldspace) var fwd = Vector3.forward; var up = Vector3.up; var followTargetRotation = FollowTargetRotation; var followTargetForward = followTargetRotation * fwd; var angle = UnityVectorExtensions.SignedAngle( fwd, followTargetForward.ProjectOntoPlane(up), up); var previousHeadingAngle = deltaTime >= 0 ? PreviousHeadingAngle : angle; var deltaHeading = angle - previousHeadingAngle; PreviousHeadingAngle = angle; // Bypass user-sourced rotation dampedTargetPos = targetPos + Quaternion.AngleAxis(deltaHeading, up) * (dampedTargetPos - targetPos); PreviousFollowTargetPosition = dampedTargetPos; GetRigPositions(out Vector3 root, out Vector3 shoulder, out Vector3 hand); // 1. Check if pivot itself is colliding with something, if yes, then move the pivot // closer to the player. The radius is bigger here than in step 2, to avoid problems // next to walls. Where the preferred distance would be pulled completely to the // player, using a bigger radius, this won't happen. hand = PullTowardsStartOnCollision(in root, in hand, in CameraCollisionFilter, CameraRadius * 1.05f); // 2. Try to place the camera to the preferred distance var camPos = hand - (followTargetForward * CameraDistance); camPos = PullTowardsStartOnCollision(in hand, in camPos, in CameraCollisionFilter, CameraRadius); curState.RawPosition = camPos; curState.RawOrientation = FollowTargetRotation; curState.ReferenceLookAt = camPos + 1000.0f * (FollowTargetRotation * Vector3.forward); curState.ReferenceUp = up; }
private float DampenValue(float deltaTime, float inputValue) { float input = inputValue * Multiplier / 10f; if (deltaTime < Epsilon) { mCurrentSpeed = 0; } else { float speed = input / deltaTime; float dampTime = Mathf.Abs(speed) < Mathf.Abs(mCurrentSpeed) ? decelTime : accelTime; speed = mCurrentSpeed + Damper.Damp(speed - mCurrentSpeed, dampTime, deltaTime); mCurrentSpeed = speed; input = speed * deltaTime; } return(input); }
/// <summary>Orients the camera to match the Follow target's orientation</summary> /// <param name="curState">The current camera state</param> /// <param name="deltaTime">Not used.</param> public override void MutateCameraState(ref CameraState curState, float deltaTime) { if (!IsValid) { return; } Quaternion dampedOrientation = FollowTargetRotation; if (deltaTime >= 0) { float t = Damper.Damp(1, m_Damping, deltaTime); dampedOrientation = Quaternion.Slerp( m_PreviousReferenceOrientation, FollowTargetRotation, t); } m_PreviousReferenceOrientation = dampedOrientation; curState.RawOrientation = dampedOrientation; }