/// <summary> /// Returns true if a given angle is pointing left of the cover. /// </summary> public bool IsLeft(float angle, float margin = 0) { float delta = Mathf.DeltaAngle(angle, Angle); return(delta >= margin && delta <= (180 - margin)); }
/// <summary> /// Calculate the shortest difference between target. /// </summary> /// <param name="vec3"></param> /// <param name="to">Target angle</param> /// <returns></returns> public static Vector3 DeltaAnglesTo(this Vector3 vec3, Vector3 to) { return(new Vector3(Mathf.DeltaAngle(vec3.x, to.x), Mathf.DeltaAngle(vec3.y, to.y), Mathf.DeltaAngle(vec3.z, to.z))); }
/// <summary> /// If segment rotation is in too big angle we straighten it /// </summary> protected Vector3 AngleLimiting(TailSegment child, Vector3 targetPos) { float angleFactor = 0f; _limiting_limitPosition = targetPos; _limiting_angle_ToTargetRot = ( Quaternion.FromToRotation ( child.ParentBone.transform.TransformDirection(child.LastKeyframeLocalPosition), targetPos - child.ParentBone.ProceduralPosition) ) * child.ParentBone.transform.rotation; _limiting_angle_targetInLocal = FEngineering.QToLocal(child.ParentBone.transform.rotation, _limiting_angle_ToTargetRot); // Quaternion.Inverse(child.ParentBone.PreviousRotation) * _limiting_angle_ToTargetRot; // Limiting all axis or one float angleDiffToInitPose = 0f; if (AngleLimitAxis.sqrMagnitude == 0f) // All axis limit angle { angleDiffToInitPose = Quaternion.Angle(_limiting_angle_targetInLocal, child.LastKeyframeLocalRotation); } else // Selective axis { #region Selective axis limits AngleLimitAxis.Normalize(); if (LimitAxisRange.x == LimitAxisRange.y) { angleDiffToInitPose = Mathf.DeltaAngle( Vector3.Scale(child.InitialLocalRotation.eulerAngles, AngleLimitAxis).magnitude, Vector3.Scale(_limiting_angle_targetInLocal.eulerAngles, AngleLimitAxis).magnitude); if (angleDiffToInitPose < 0f) { angleDiffToInitPose = -angleDiffToInitPose; } } else { angleDiffToInitPose = Mathf.DeltaAngle( Vector3.Scale(child.InitialLocalRotation.eulerAngles, AngleLimitAxis).magnitude, Vector3.Scale(_limiting_angle_targetInLocal.eulerAngles, AngleLimitAxis).magnitude); if (angleDiffToInitPose > LimitAxisRange.x && angleDiffToInitPose < LimitAxisRange.y) { angleDiffToInitPose = 0f; } if (angleDiffToInitPose < 0) { angleDiffToInitPose = -angleDiffToInitPose; } } #endregion } #region Debug //Debug.Log("Atarget in local = " + // FEngineering.WrapVector(_limiting_angle_targetInLocal.eulerAngles) + " last key local = " + // FEngineering.WrapVector(child.lastKeyframeLocalRotation.eulerAngles) + " angle = " + angleDiffToInitPose); #endregion // Finding rotate back to limited angle coordinates if (angleDiffToInitPose > AngleLimit) { float exceededAngle = Mathf.Abs(Mathf.DeltaAngle(angleDiffToInitPose, AngleLimit)); angleFactor = Mathf.InverseLerp(0f, AngleLimit, exceededAngle); // percentage value (0-1) from target rotation to limit #region Debug //Debug.DrawLine(child.ParentBone.ParentBone.transform.position + child.ParentBone.ParentBone.ProceduralRotation * child.ParentBone.transform.localPosition, //child.ProceduralPosition, Color.red, 1f); //Debug.Log("[" + child.Index + "] diff = " // + angleDiffToInitPose + " exc = " // + exceededAngle + " fact = " // + angleFactor); #endregion if (LimitSmoothing > Mathf.Epsilon) { float smooth = Mathf.Lerp(55f, 15f, LimitSmoothing); _limiting_angle_newLocal = Quaternion.SlerpUnclamped(_limiting_angle_targetInLocal, child.LastKeyframeLocalRotation, deltaForLerps * smooth * angleFactor); } else { _limiting_angle_newLocal = Quaternion.SlerpUnclamped(_limiting_angle_targetInLocal, child.LastKeyframeLocalRotation, angleFactor); } _limiting_angle_ToTargetRot = FEngineering.QToWorld(child.ParentBone.transform.rotation, _limiting_angle_newLocal); _limiting_limitPosition = child.ParentBone.ProceduralPosition + _limiting_angle_ToTargetRot * Vector3.Scale(child.transform.lossyScale, child.LastKeyframeLocalPosition); } if (angleFactor > Mathf.Epsilon) { return(_limiting_limitPosition); } else { return(targetPos); } }
//Calculates Pinch and Turn - This should be used inside LateUpdate void Calculate() { pinchDistance = pinchDistanceDelta = 0; turnAngle = turnAngleDelta = 0; // if two fingers are touching the screen at the same time ... if (Input.touchCount == 2) { //update multiTouch if (multiTouch == MultiTouchState.Ended) { multiTouch = MultiTouchState.Init; MultiTouchInitStart = Time.time; } else if (multiTouch == MultiTouchState.Init && Time.time - MultiTouchInitStart > MultiTouchInitDelay) { multiTouch = MultiTouchState.Began; } else if (multiTouch == MultiTouchState.Began) { multiTouch = MultiTouchState.Ongoing; } Touch touch1 = Input.touches[0]; Touch touch2 = Input.touches[1]; // ... if at least one of them moved ... if (touch1.phase == TouchPhase.Moved || touch2.phase == TouchPhase.Moved) { // ... check the delta distance between them ... pinchDistance = Vector2.Distance(touch1.position, touch2.position); float prevDistance = Vector2.Distance(touch1.position - touch1.deltaPosition, touch2.position - touch2.deltaPosition); pinchDistanceDelta = pinchDistance - prevDistance; // ... if it's greater than a minimum threshold, it's a pinch! if (Mathf.Abs(pinchDistanceDelta) > minPinchDistance) { pinchDistanceDelta *= pinchRatio; } else { pinchDistance = pinchDistanceDelta = 0; } // ... check the delta angle between them ... turnAngle = Angle(touch1.position, touch2.position); float prevTurn = Angle(touch1.position - touch1.deltaPosition, touch2.position - touch2.deltaPosition); turnAngleDelta = Mathf.DeltaAngle(prevTurn, turnAngle); // ... if it's greater than a minimum threshold, it's a turn! if (Mathf.Abs(turnAngleDelta) > minTurnAngle) { turnAngleDelta *= pinchTurnRatio; } else { turnAngle = turnAngleDelta = 0; } } } else { multiTouch = MultiTouchState.Ended; } }
protected override void FollowTarget(float deltaTime) { // if no target then early out as there is nothing to do if (!(deltaTime > 0) || target == null) { return; } // initialise some vars, we'll be modifying these in a moment var targetForward = target.forward; var targetUp = target.up; if (followVelocity) { // in follow velocity mode, the camera's rotation is aligned towards the object's velocity direction // but only if the object is traveling faster than a given threshold. if (target.rigidbody.velocity.magnitude > targetVelocityLowerLimit) { // velocity is high enough, so we'll use the target's velocty targetForward = target.rigidbody.velocity.normalized; targetUp = Vector3.up; } else { targetUp = Vector3.up; } currentTurnAmount = Mathf.SmoothDamp(currentTurnAmount, 1, ref turnSpeedVelocityChange, smoothTurnTime); } else { // we're in 'follow rotation' mode, where the camera rig's rotation follows the object's rotation. // This section allows the camera to stop following the target's rotation when the target is spinning too fast. // eg when a car has been knocked into a spin. The camera will resume following the rotation // of the target when the target's angular velocity slows below the threshold. var currentFlatAngle = Mathf.Atan2(targetForward.x, targetForward.z) * Mathf.Rad2Deg; if (spinTurnLimit > 0) { var targetSpinSpeed = Mathf.Abs(Mathf.DeltaAngle(lastFlatAngle, currentFlatAngle)) / deltaTime; var desiredTurnAmount = Mathf.InverseLerp(spinTurnLimit, spinTurnLimit * 0.75f, targetSpinSpeed); var turnReactSpeed = (currentTurnAmount > desiredTurnAmount ? .1f : 1f); currentTurnAmount = Mathf.SmoothDamp(currentTurnAmount, desiredTurnAmount, ref turnSpeedVelocityChange, turnReactSpeed); } else { currentTurnAmount = 1; } lastFlatAngle = currentFlatAngle; } // camera position moves towards target position: transform.position = Vector3.Lerp(transform.position, target.position, deltaTime * moveSpeed); // camera's rotation is split into two parts, which can have independend speed settings: // rotating towards the target's forward direction (which encompasses its 'yaw' and 'pitch') if (!followTilt) { targetForward.y = 0; if (targetForward.sqrMagnitude < float.Epsilon) { targetForward = transform.forward; } } var rollRotation = Quaternion.LookRotation(targetForward, rollUp); // and aligning with the target object's up direction (i.e. its 'roll') rollUp = rollSpeed > 0 ? Vector3.Slerp(rollUp, targetUp, rollSpeed * Time.deltaTime) : Vector3.up; transform.rotation = Quaternion.Lerp(transform.rotation, rollRotation, turnSpeed * currentTurnAmount * Time.smoothDeltaTime); }
/// <summary> /// Update the X axis and calculate the heading. This can be called by a delegate /// with a custom axis. /// <param name="deltaTime">Used for damping. If less than 0, no damping is done.</param> /// <param name="up">World Up, set by the CinemachineBrain</param> /// <param name="axis"></param> /// <returns>Axis value</returns> /// </summary> public float UpdateHeading(float deltaTime, Vector3 up, ref AxisState axis) { // Only read joystick when game is playing if (deltaTime >= 0 || CinemachineCore.Instance.IsLive(VirtualCamera)) { var xAxisInput = false; xAxisInput |= axis.Update(deltaTime); if (xAxisInput) { mLastHeadingAxisInputTime = Time.time; mHeadingRecenteringVelocity = 0; } } var targetHeading = GetTargetHeading(axis.Value, GetReferenceOrientation(up), deltaTime); if (deltaTime < 0) { mHeadingRecenteringVelocity = 0; if (m_RecenterToTargetHeading.m_enabled) { axis.Value = targetHeading; } } else { // Recentering if (m_BindingMode != BindingMode.SimpleFollowWithWorldUp && m_RecenterToTargetHeading.m_enabled && Time.time > mLastHeadingAxisInputTime + m_RecenterToTargetHeading.m_RecenterWaitTime) { // Scale value determined heuristically, to account for accel/decel var recenterTime = m_RecenterToTargetHeading.m_RecenteringTime / 3f; if (recenterTime <= deltaTime) { axis.Value = targetHeading; } else { var headingError = Mathf.DeltaAngle(axis.Value, targetHeading); var absHeadingError = Mathf.Abs(headingError); if (absHeadingError < UnityVectorExtensions.Epsilon) { axis.Value = targetHeading; mHeadingRecenteringVelocity = 0; } else { var scale = deltaTime / recenterTime; var desiredVelocity = Mathf.Sign(headingError) * Mathf.Min(absHeadingError, absHeadingError * scale); // Accelerate to the desired velocity var accel = desiredVelocity - mHeadingRecenteringVelocity; if (desiredVelocity < 0 && accel < 0 || desiredVelocity > 0 && accel > 0) { desiredVelocity = mHeadingRecenteringVelocity + desiredVelocity * scale; } axis.Value += desiredVelocity; mHeadingRecenteringVelocity = desiredVelocity; } } } } var finalHeading = axis.Value; if (m_BindingMode == BindingMode.SimpleFollowWithWorldUp) { axis.Value = 0; } return(finalHeading); }
private void ProcessInput(ref HumanController.InputSample sample) { bool flag; bool flag1; CCMotor.InputFrame movementScale = new CCMotor.InputFrame(); float single; float single1; CCMotor cCMotor = base.ccmotor; if (!cCMotor) { flag1 = false; flag = true; } else { flag = cCMotor.isGrounded; flag1 = cCMotor.isSliding; if (!flag && !flag1) { sample.sprint = false; sample.crouch = false; sample.aim = false; sample.info__crouchBlocked = false; if (!this.wasInAir) { this.wasInAir = true; this.magnitudeAir = cCMotor.input.moveDirection.magnitude; this.midairStartPos = base.transform.position; } this.lastFrameVelocity = cCMotor.velocity; } else if (this.wasInAir) { this.wasInAir = false; this.magnitudeAir = 1f; this.landingSpeedPenaltyTime = 0f; if (base.transform.position.y < this.midairStartPos.y && Mathf.Abs(base.transform.position.y - this.midairStartPos.y) > 2f) { base.idMain.GetLocal <FallDamage>().SendFallImpact(this.lastFrameVelocity); } this.lastFrameVelocity = Vector3.zero; this.midairStartPos = Vector3.zero; } bool flag2 = (sample.crouch ? true : sample.info__crouchBlocked); movementScale.jump = sample.jump; movementScale.moveDirection.x = sample.strafe; movementScale.moveDirection.y = 0f; movementScale.moveDirection.z = sample.walk; movementScale.crouchSpeed = (!sample.crouch ? 1f : -1f); if (movementScale.moveDirection == Vector3.zero) { this.sprinting = false; this.exitingSprint = false; this.sprintTime = 0f; this.crouchTime = (!sample.crouch ? 0f : this.controlConfig.curveCrouchMulSpeedByTime.GetEndTime()); this.magnitudeAir = 1f; } else { float single2 = movementScale.moveDirection.magnitude; if (single2 < 1f) { movementScale.moveDirection = movementScale.moveDirection / single2; single2 = single2 * single2; movementScale.moveDirection = movementScale.moveDirection * single2; } else if (single2 > 1f) { movementScale.moveDirection = movementScale.moveDirection / single2; } if (HumanController.InputSample.MovementScale < 1f) { if (HumanController.InputSample.MovementScale <= 0f) { movementScale.moveDirection = Vector3.zero; } else { movementScale.moveDirection = movementScale.moveDirection * HumanController.InputSample.MovementScale; } } Vector3 vector3 = movementScale.moveDirection; vector3.x = vector3.x * this.controlConfig.sprintScaleX; vector3.z = vector3.z * this.controlConfig.sprintScaleY; if (!sample.sprint || flag2 || sample.aim) { sample.sprint = false; single = -Time.deltaTime; } else { single = Time.deltaTime * this.sprintInMulTime; } movementScale.moveDirection = movementScale.moveDirection + (vector3 * this.controlConfig.curveSprintAddSpeedByTime.EvaluateClampedTime(ref this.sprintTime, single)); single1 = (!flag2 ? -Time.deltaTime : Time.deltaTime * this.crouchInMulTime); movementScale.moveDirection = movementScale.moveDirection * this.controlConfig.curveCrouchMulSpeedByTime.EvaluateClampedTime(ref this.crouchTime, single1); movementScale.moveDirection = base.transform.TransformDirection(movementScale.moveDirection); if (!this.wasInAir) { movementScale.moveDirection = movementScale.moveDirection * this.controlConfig.curveLandingSpeedPenalty.EvaluateClampedTime(ref this.landingSpeedPenaltyTime, Time.deltaTime); } else { float single3 = movementScale.moveDirection.magnitude; if (!Mathf.Approximately(single3, this.magnitudeAir)) { movementScale.moveDirection = movementScale.moveDirection / single3; movementScale.moveDirection = movementScale.moveDirection * this.magnitudeAir; } } } if (DebugInput.GetKey(KeyCode.H)) { movementScale.moveDirection = movementScale.moveDirection * 100f; } cCMotor.input = movementScale; if (cCMotor.stepMode == CCMotor.StepMode.Elsewhere) { cCMotor.Step(); } } Character character = base.idMain; Crouchable crouchable = character.crouchable; if (character) { Angle2 angle2 = base.eyesAngles; Angle2 angle21 = base.eyesAngles; angle2.yaw = Mathf.DeltaAngle(0f, angle21.yaw + sample.yaw); angle2.pitch = base.ClampPitch(angle2.pitch + sample.pitch); base.eyesAngles = angle2; ushort num = character.stateFlags.flags; if (crouchable) { this.crouch_smoothing.AddSeconds((double)Time.deltaTime); crouchable.LocalPlayerUpdateCrouchState(cCMotor, ref sample.crouch, ref sample.info__crouchBlocked, ref this.crouch_smoothing); } int num1 = (!sample.aim ? 0 : 4) | (!sample.sprint ? 0 : 2) | (!sample.attack ? 0 : 8) | (!sample.attack2 ? 0 : 256) | (!sample.crouch ? 0 : 1) | (sample.strafe != 0f || sample.walk != 0f ? 64 : 0) | (!LockCursorManager.IsLocked() ? 128 : 0) | (!flag ? 16 : 0) | (!flag1 ? 0 : 32) | (!this.bleeding ? 0 : 512) | (!sample.lamp ? 0 : 2048) | (!sample.laser ? 0 : 4096) | (!sample.info__crouchBlocked ? 0 : 1024); character.stateFlags = num1; if (num != num1) { character.Signal_State_FlagsChanged(false); } } this.crouch_was_blocked = sample.info__crouchBlocked; if (sample.inventory) { RPOS.Toggle(); } if (Input.GetKeyDown(KeyCode.Escape)) { RPOS.Hide(); } }
private Vector3 m_RollUp = Vector3.up; // The roll of the camera around the z axis ( generally this will always just be up ) //private Vector3 targetAngle = new Vector3(4.50617f, 179.999f, -341.47f); protected override void FollowTarget(float deltaTime) { // if no target, or no time passed then we quit early, as there is nothing to do if (!(deltaTime > 0) || m_Target == null) { return; } // initialise some vars, we'll be modifying these in a moment var targetForward = m_Target.forward; var targetUp = m_Target.up; if (m_FollowVelocity && Application.isPlaying) { // in follow velocity mode, the camera's rotation is aligned towards the object's velocity direction // but only if the object is traveling faster than a given threshold. if (targetRigidbody.velocity.magnitude > m_TargetVelocityLowerLimit) { // velocity is high enough, so we'll use the target's velocty targetForward = targetRigidbody.velocity.normalized; //targetAngle = targetRigidbody.velocity.normalized; targetUp = Vector3.up; } else { targetUp = Vector3.up; } m_CurrentTurnAmount = Mathf.SmoothDamp(m_CurrentTurnAmount, 1, ref m_TurnSpeedVelocityChange, m_SmoothTurnTime); } else { // we're in 'follow rotation' mode, where the camera rig's rotation follows the object's rotation. // This section allows the camera to stop following the target's rotation when the target is spinning too fast. // eg when a car has been knocked into a spin. The camera will resume following the rotation // of the target when the target's angular velocity slows below the threshold. var currentFlatAngle = Mathf.Atan2(targetForward.x, targetForward.z) * Mathf.Rad2Deg; //var currentFlatAngle = Mathf.Atan2(targetAngle.x, targetAngle.z)*Mathf.Rad2Deg; if (m_SpinTurnLimit > 0) { var targetSpinSpeed = Mathf.Abs(Mathf.DeltaAngle(m_LastFlatAngle, currentFlatAngle)) / deltaTime; var desiredTurnAmount = Mathf.InverseLerp(m_SpinTurnLimit, m_SpinTurnLimit * 0.75f, targetSpinSpeed); var turnReactSpeed = (m_CurrentTurnAmount > desiredTurnAmount ? .1f : 1f); if (Application.isPlaying) { m_CurrentTurnAmount = Mathf.SmoothDamp(m_CurrentTurnAmount, desiredTurnAmount, ref m_TurnSpeedVelocityChange, turnReactSpeed); } else { // for editor mode, smoothdamp won't work because it uses deltaTime internally m_CurrentTurnAmount = desiredTurnAmount; } } else { m_CurrentTurnAmount = 1; } m_LastFlatAngle = currentFlatAngle; } // camera position moves towards target position: //transform.position = Vector3.Lerp(transform.position, m_Target.position, deltaTime*m_MoveSpeed); //Vector3 targetPosition = new Vector3 (-510, -65, 461); transform.position = Vector3.Lerp(transform.position, m_Target.position, deltaTime * m_MoveSpeed); // camera's rotation is split into two parts, which can have independend speed settings: // rotating towards the target's forward direction (which encompasses its 'yaw' and 'pitch') if (!m_FollowTilt) { targetForward.y = 0; if (targetForward.sqrMagnitude < float.Epsilon) { targetForward = transform.forward; } //targetAngle.y = 0; //if (targetAngle.sqrMagnitude < float.Epsilon) { // targetAngle = transform.forward; //} } var rollRotation = Quaternion.LookRotation(targetForward, m_RollUp); //var rollRotation = Quaternion.LookRotation(targetAngle, m_RollUp); // and aligning with the target object's up direction (i.e. its 'roll') m_RollUp = m_RollSpeed > 0 ? Vector3.Slerp(m_RollUp, targetUp, m_RollSpeed * deltaTime) : Vector3.up; transform.rotation = Quaternion.Lerp(transform.rotation, rollRotation, m_TurnSpeed * m_CurrentTurnAmount * deltaTime); }
void Update() { if (Input.touchCount == 2) { Touch touch1 = Input.touches[0]; Touch touch2 = Input.touches[1]; Vector2 pos1 = touch1.position; Vector2 pos2 = touch2.position; Vector2 delta1 = pos1 - lastTouchPos1; Vector2 delta2 = pos2 - lastTouchPos2; if (firstTouch) { firstTouch = false; //for rotate initPos1 = pos1; initPos2 = pos2; initGradient = (pos1 - pos2).normalized; float curX = pos1.x - pos2.x; float curY = pos1.y - pos2.y; prevAngle = IT_Gesture.VectorToAngle(new Vector2(curX, curY)); } if (touch1.phase == TouchPhase.Moved && touch2.phase == TouchPhase.Moved) { float dot = Vector2.Dot(delta1, delta2); if (dot < .5f) { Vector2 grad1 = (pos1 - initPos1).normalized; Vector2 grad2 = (pos2 - initPos2).normalized; float dot1 = Vector2.Dot(grad1, initGradient); float dot2 = Vector2.Dot(grad2, initGradient); //rotate if (dot1 < 0.7f && dot2 < 0.7f) { float curX = pos1.x - pos2.x; float curY = pos1.y - pos2.y; float curAngle = IT_Gesture.VectorToAngle(new Vector2(curX, curY)); float val = Mathf.DeltaAngle(curAngle, prevAngle); if (rotationSmoothing == _SmoothMethod.None) { RotateInfo rotateInfo = new RotateInfo(val, pos1, pos2); IT_Gesture.Rotate(rotateInfo); } else { if (Mathf.Abs(val) > 0) { AddRotVal(val); } float valueAvg = GetAverageValue(); if (valueAvg != 0) { RotateInfo rotateInfo = new RotateInfo(valueAvg, pos1, pos2); IT_Gesture.Rotate(rotateInfo); } } prevAngle = curAngle; } //pinch else { Vector2 curDist = pos1 - pos2; Vector2 prevDist = (pos1 - delta1) - (pos2 - delta2); float pinch = prevDist.magnitude - curDist.magnitude; if (Mathf.Abs(pinch) > 0.5f) { PinchInfo pinchInfo = new PinchInfo(pinch, pos1, pos2); IT_Gesture.Pinch(pinchInfo); } } } } lastTouchPos1 = pos1; lastTouchPos2 = pos2; } else { if (!firstTouch) { firstTouch = true; if (rotationSmoothing != _SmoothMethod.None) { ClearRotVal(); } } } }
public void UpdateCharacter(int charId, Vector3 position, float direction, int walking, Quaternion headRot, Vector3 velocity, float crouchfactor) { ////Debug.Log ("Update called for " + charId + " at " + position.x + ", " + position.y + ", " + position.z); // Don't update self if using client-side prediction if (CurrentGameState != Game.GameStates.LevelLoaded || MyPlayer == null || (ClientSidePrediction && charId.Equals(((Character)MyPlayer).Id)) || !SceneCharacters.ContainsKey(charId) ) { return; } SceneCharacter3D character = SceneCharacters[charId]; ObjectState charState = new ObjectState(charId, position, direction, headRot, velocity, crouchfactor, walking); // TODO: fix this to call a special method just updating the legs // character.GetComponent<SceneCharacter3D>().Move(1f, 0f, Time.deltaTime, false); if (!CharacterInterpolation) { character.transform.position = position; character.state.velocity = velocity; character.state.angle = direction; character.head.transform.localRotation = headRot; character.crouch_factor = crouchfactor; character.transform.localEulerAngles = new Vector3(0, direction, 0); return; } // 7A) Store the character state from the server if (CharacterIntendedStates.ContainsKey(charId)) { CharacterIntendedStates.Remove(charId); CharacterPositionDiffs.Remove(charId); CharacterDirectionDiffs.Remove(charId); CharacterHeadRotDiffs.Remove(charId); CharacterCrouchFactorDiffs.Remove(charId); } CharacterIntendedStates.Add(charId, charState); // 7B) Calculate the position difference Vector3 currentCharPosition = character.transform.position; Vector3 intendedCharacterPosition = charState.Position; CharacterPositionDiffs.Add(charId, new Vector3( intendedCharacterPosition.x - currentCharPosition.x, intendedCharacterPosition.y - currentCharPosition.y, intendedCharacterPosition.z - currentCharPosition.z )); // Calculate the direction difference float currentCharDirection = character.transform.localEulerAngles.y; float intendedCharacterDirection = charState.Angle; /*CharacterDirectionDiffs.Add(charId, new Vector3( * intendedCharacterDirection.x - currentCharDirection.x, * intendedCharacterDirection.y - currentCharDirection.y, * intendedCharacterDirection.z - currentCharDirection.z * )); */ // TODO: use Mathf.DeltaAngle instead and test //float phi = Mathf.Abs(currentCharDirection - intendedCharacterDirection) % 360f; //float dist = phi > 180 ? 360 - phi : phi; float dist = Mathf.DeltaAngle(currentCharDirection, intendedCharacterDirection); CharacterDirectionDiffs.Add(charId, dist); Quaternion currentCharHeadRot = character.head.transform.localRotation; Quaternion intendedCharacterHeadRot = charState.HeadRot; CharacterHeadRotDiffs.Add(charId, new Quaternion( intendedCharacterHeadRot.x - currentCharHeadRot.x, intendedCharacterHeadRot.y - currentCharHeadRot.y, intendedCharacterHeadRot.z - currentCharHeadRot.z, intendedCharacterHeadRot.w - currentCharHeadRot.w )); float currentCharCrouchFactor = character.crouch_factor; float intendedCharacterCrouchFactor = charState.CrouchFactor; CharacterCrouchFactorDiffs.Add(charId, intendedCharacterCrouchFactor - currentCharCrouchFactor); }
private void UpdateStunts() { //score = score; if (ghost) { return; } if (!online) { score = Mathf.Lerp(score, 0, Time.deltaTime * 0.01f); } var euler = transform.eulerAngles; var grounded = Time.time - groundedTime2 < .1f; //if (grounded) //{ // if (skid2 > 1 ) // tempScore += Time.deltaTime * 20; // //tempScore += Math.Abs(Mathf.DeltaAngle(oldRot.x, euler.x)) + Mathf.Abs(Mathf.DeltaAngle(oldRot.z, euler.z)); // //print(Mathf.Abs(Mathf.DeltaAngle(oldRot.x, euler.x)) + Math.Abs(Mathf.DeltaAngle(oldRot.y, euler.y)) + Mathf.Abs(Mathf.DeltaAngle(oldRot.z, euler.z))); // //print("local euler:"+transform.localEulerAngles); // //print("euler:"+transform.eulerAngles); //} if (!grounded) { tempScore += Time.deltaTime * 50; tempScore += Mathf.Abs(Mathf.DeltaAngle(oldRot.x, euler.x)) + Math.Abs(Mathf.DeltaAngle(oldRot.y, euler.y)) + Mathf.Abs(Mathf.DeltaAngle(oldRot.z, euler.z)) / 30f; } //if (_Game.backTime) //oldTempScore=tempScore = 0; var changed = Math.Abs(oldTempScore - tempScore) > .01f; if (changed && tempScore > 100) { var t = ((int)tempScore).ToString(); //_Loader.CenterText.text = t; //_Loader.CenterTextBackground.enabled = _Loader.CenterText.enabled = true; _Player.hud.PlayScore(t, Color.white); } if (grounded && tempScore > 100 && !changed) { //_Game.centerText("Got " + ((int) tempScore) + "!", .1f); //_Player.hud.PlayScore(((int)tempScore).ToString(), Color.blue); //score += tempScore; AddScore(tempScore, Color.blue); } //else if (!changed) // _Player.hud.PlayScore(((int)tempScore).ToString(), Color.red); if (!changed && tempScore > 0) { //print(Math.Abs(oldTempScore - tempScore)); tempScore = 0; } //if (!online) //if (online) //{ // _Game.scoreText.enabled = true; // _Game.scoreText.text = ((int)score).ToString(); //} oldRot = euler; oldTempScore = tempScore; }
void Update() { //71 notches on thing // print(plane.gameObject.transform.localEulerAngles.y+"\t"+level.y+"\t"+Mathf.DeltaAngle(plane.gameObject.transform.localEulerAngles.y, level.y )); hud.transform.localPosition = new Vector3(0, Mathf.DeltaAngle(plane.gameObject.transform.localEulerAngles.y, level.y) * -5.785f + 525, 0); }
public void Solve(bool isLeft) { chestRotation = Quaternion.LookRotation(rootRotation * chestForwardAxis, rootRotation * chestUpAxis); chestForward = chestRotation * Vector3.forward; chestUp = chestRotation * Vector3.up; //Debug.DrawRay (Vector3.up * 2f, chestForward); //Debug.DrawRay (Vector3.up * 2f, chestUp); if (hasShoulder && shoulderRotationWeight > 0f) { switch (shoulderRotationMode) { case ShoulderRotationMode.YawPitch: Vector3 sDir = position - shoulder.solverPosition; sDir = sDir.normalized; // Shoulder Yaw float yOA = isLeft? yawOffsetAngle: -yawOffsetAngle; Quaternion yawOffset = Quaternion.AngleAxis((isLeft? -90f: 90f) + yOA, chestUp); Quaternion workingSpace = yawOffset * chestRotation; //Debug.DrawRay(Vector3.up * 2f, workingSpace * Vector3.forward); //Debug.DrawRay(Vector3.up * 2f, workingSpace * Vector3.up); Vector3 sDirWorking = Quaternion.Inverse(workingSpace) * sDir; //Debug.DrawRay(Vector3.up * 2f, sDirWorking); float yaw = Mathf.Atan2(sDirWorking.x, sDirWorking.z) * Mathf.Rad2Deg; float dotY = Vector3.Dot(sDirWorking, Vector3.up); dotY = 1f - Mathf.Abs(dotY); yaw *= dotY; yaw -= yOA; float yawLimitMin = isLeft? -20f: -50f; float yawLimitMax = isLeft? 50f: 20f; yaw = DamperValue(yaw, yawLimitMin - yOA, yawLimitMax - yOA, 0.7f); // back, forward Vector3 f = shoulder.solverRotation * shoulder.axis; Vector3 t = workingSpace * (Quaternion.AngleAxis(yaw, Vector3.up) * Vector3.forward); Quaternion yawRotation = Quaternion.FromToRotation(f, t); //Debug.DrawRay(Vector3.up * 2f, f, Color.red); //Debug.DrawRay(Vector3.up * 2f, t, Color.green); //Debug.DrawRay(Vector3.up * 2f, yawRotation * Vector3.forward, Color.blue); //Debug.DrawRay(Vector3.up * 2f, yawRotation * Vector3.up, Color.green); //Debug.DrawRay(Vector3.up * 2f, yawRotation * Vector3.right, Color.red); // Shoulder Pitch Quaternion pitchOffset = Quaternion.AngleAxis(isLeft? -90f: 90f, chestUp); workingSpace = pitchOffset * chestRotation; workingSpace = Quaternion.AngleAxis(isLeft? pitchOffsetAngle: -pitchOffsetAngle, chestForward) * workingSpace; //Debug.DrawRay(Vector3.up * 2f, workingSpace * Vector3.forward); //Debug.DrawRay(Vector3.up * 2f, workingSpace * Vector3.up); sDir = position - (shoulder.solverPosition + chestRotation * (isLeft? Vector3.right: Vector3.left) * mag); sDirWorking = Quaternion.Inverse(workingSpace) * sDir; //Debug.DrawRay(Vector3.up * 2f, sDirWorking); float pitch = Mathf.Atan2(sDirWorking.y, sDirWorking.z) * Mathf.Rad2Deg; pitch -= pitchOffsetAngle; pitch = DamperValue(pitch, -45f - pitchOffsetAngle, 45f - pitchOffsetAngle); Quaternion pitchRotation = Quaternion.AngleAxis(-pitch, workingSpace * Vector3.right); //Debug.DrawRay(Vector3.up * 2f, pitchRotation * Vector3.forward, Color.green); //Debug.DrawRay(Vector3.up * 2f, pitchRotation * Vector3.up, Color.green); // Rotate bones Quaternion sR = pitchRotation * yawRotation; if (shoulderRotationWeight * positionWeight < 1f) { sR = Quaternion.Lerp(Quaternion.identity, sR, shoulderRotationWeight * positionWeight); } VirtualBone.RotateBy(bones, sR); Stretching(); // Solve trigonometric VirtualBone.SolveTrigonometric(bones, 1, 2, 3, position, GetBendNormal(position - upperArm.solverPosition), positionWeight); float p = Mathf.Clamp(pitch * 2f * positionWeight, 0f, 180f); shoulder.solverRotation = Quaternion.AngleAxis(p, shoulder.solverRotation * (isLeft? shoulder.axis: -shoulder.axis)) * shoulder.solverRotation; upperArm.solverRotation = Quaternion.AngleAxis(p, upperArm.solverRotation * (isLeft? upperArm.axis: -upperArm.axis)) * upperArm.solverRotation; // Additional pass to reach with the shoulders //VirtualBone.SolveTrigonometric(bones, 0, 1, 3, position, Vector3.Cross(upperArm.solverPosition - shoulder.solverPosition, hand.solverPosition - shoulder.solverPosition), positionWeight * 0.5f); break; case ShoulderRotationMode.FromTo: Quaternion shoulderRotation = shoulder.solverRotation; Quaternion r = Quaternion.FromToRotation((upperArm.solverPosition - shoulder.solverPosition).normalized + chestForward, position - shoulder.solverPosition); r = Quaternion.Slerp(Quaternion.identity, r, 0.5f * shoulderRotationWeight * positionWeight); VirtualBone.RotateBy(bones, r); Stretching(); VirtualBone.SolveTrigonometric(bones, 0, 2, 3, position, Vector3.Cross(forearm.solverPosition - shoulder.solverPosition, hand.solverPosition - shoulder.solverPosition), 0.5f * shoulderRotationWeight * positionWeight); VirtualBone.SolveTrigonometric(bones, 1, 2, 3, position, GetBendNormal(position - upperArm.solverPosition), positionWeight); // Twist shoulder and upper arm bones when holding hands up Quaternion q = Quaternion.Inverse(Quaternion.LookRotation(chestUp, chestForward)); Vector3 vBefore = q * (shoulderRotation * shoulder.axis); Vector3 vAfter = q * (shoulder.solverRotation * shoulder.axis); float angleBefore = Mathf.Atan2(vBefore.x, vBefore.z) * Mathf.Rad2Deg; float angleAfter = Mathf.Atan2(vAfter.x, vAfter.z) * Mathf.Rad2Deg; float pitchAngle = Mathf.DeltaAngle(angleBefore, angleAfter); if (isLeft) { pitchAngle = -pitchAngle; } pitchAngle = Mathf.Clamp(pitchAngle * 2f * positionWeight, 0f, 180f); shoulder.solverRotation = Quaternion.AngleAxis(pitchAngle, shoulder.solverRotation * (isLeft? shoulder.axis: -shoulder.axis)) * shoulder.solverRotation; upperArm.solverRotation = Quaternion.AngleAxis(pitchAngle, upperArm.solverRotation * (isLeft? upperArm.axis: -upperArm.axis)) * upperArm.solverRotation; break; } } else { Stretching(); // Solve arm trigonometric VirtualBone.SolveTrigonometric(bones, 1, 2, 3, position, GetBendNormal(position - upperArm.solverPosition), positionWeight); } // Fix forearm twist relative to upper arm Quaternion forearmFixed = upperArm.solverRotation * forearmRelToUpperArm; Quaternion fromTo = Quaternion.FromToRotation(forearmFixed * forearm.axis, hand.solverPosition - forearm.solverPosition); RotateTo(forearm, fromTo * forearmFixed, positionWeight); // Set hand rotation if (rotationWeight >= 1f) { hand.solverRotation = rotation; } else if (rotationWeight > 0f) { hand.solverRotation = Quaternion.Lerp(hand.solverRotation, rotation, rotationWeight); } }
/// <summary> /// Returns true if a given angle is pointing right of the cover. /// </summary> public bool IsRight(float angle, float margin = 0) { float delta = Mathf.DeltaAngle(angle, Angle); return(delta >= (-180 + margin) && delta <= -margin); }
/// <summary> /// There is a lot of code in here, but it's really just controlling the visual effect in the menu, and a little bit of logic. There are also responders for click events in if blocks. Easy enough. /// </summary> public override void DoUpdate(SceneManager context) { if (mode == MenuMode.Main) { if (labs.IsClicked) { hike.Invisible = true; mode = MenuMode.Labs; menu.gameObject.SetActive(true); hikeMenu.gameObject.SetActive(false); hikeTitleAlphaTarget = -1; labsTitleAlphaTarget = -1f; springMenu.minYaw = springMenu.maxYaw = -7; //Debug.Log("labs"); } if (hike.IsClicked) { labs.Invisible = true; mode = MenuMode.Hike; hikeMenu.gameObject.SetActive(true); menu.gameObject.SetActive(false); labsTitleAlphaTarget = -1; hikeTitleAlphaTarget = -1f; springMenu.minYaw = springMenu.maxYaw = 7; //Debug.Log("labs"); } } if (mode == MenuMode.Labs || (mode == MenuMode.Main && labs.IsTarget)) //|| (mode == MenuMode.Main && (labs.IsTarget || (mode == MenuMode.Main && springMenu.Direction == -1 ) ) ) // realTarget = 1; { if (fadeValue < 0) { spring = 0.75f; //targetFade = 0; } else { spring = 0.25f; //targetFade = 1; } targetFade = 1; } else if (mode == MenuMode.Hike || (mode == MenuMode.Main && hike.IsTarget)) //|| (mode == MenuMode.Main && ( hike.IsTarget || (mode == MenuMode.Main && springMenu.Direction == 1) ) ) //realTarget = -1; { if (fadeValue > 0) { spring = 0.75f; //targetFade = 0; } else { spring = 0.25f; //targetFade = -1; } targetFade = -1; } else { targetFade = 0; //realTarget = 0; } if (mode == MenuMode.Labs) { if (back.IsClicked) { hike.Invisible = false; mode = MenuMode.Main; //menu.gameObject.SetActive(false); springMenu.minYaw = -7; springMenu.maxYaw = 7; labsTitleAlphaTarget = 1; hikeTitleAlphaTarget = 1; //Debug.Log("labs"); } else if (targeting.IsClicked) { SceneManager.Instance.StateTransition(SceneManager.Instance.targetScene); //Debug.Log("labs"); } else if (motion.IsClicked) { SceneManager.Instance.StateTransition(SceneManager.Instance.minecartScene); //Debug.Log("labs"); } else if (text.IsClicked) { SceneManager.Instance.StateTransition(SceneManager.Instance.visionScene); //Debug.Log("labs"); } else if (relativity.IsClicked) { SceneManager.Instance.StateTransition(SceneManager.Instance.relativityScene); //Debug.Log("labs"); } else if (tracking.IsClicked) { SceneManager.Instance.StateTransition(SceneManager.Instance.trackingScene); //Debug.Log("labs"); } } if (mode == MenuMode.Hike) { if (hikeBack.IsClicked) { labs.Invisible = false; mode = MenuMode.Main; //hikeMenu.gameObject.SetActive(false); springMenu.minYaw = -7; springMenu.maxYaw = 7; labsTitleAlphaTarget = 1; hikeTitleAlphaTarget = 1; //Debug.Log("labs"); } else if (hike1.IsClicked) { SceneManager.Instance.StateTransition(SceneManager.Instance.redwoodScene, Color.black, 0); } else if (hike2.IsClicked) { SceneManager.Instance.StateTransition(SceneManager.Instance.redwoodScene, Color.black, 1); } else if (hike3.IsClicked) { SceneManager.Instance.StateTransition(SceneManager.Instance.redwoodScene, Color.black, 2); } else if (hike4.IsClicked) { SceneManager.Instance.StateTransition(SceneManager.Instance.redwoodScene, Color.black, 3); } else if (hike5.IsClicked) { SceneManager.Instance.StateTransition(SceneManager.Instance.redwoodScene, Color.black, 4); } } //if( Mathf.Abs(fadeValue) < 0.05f ){ // targetFade = realTarget; //} hikeTitleAlpha = Smoothing.SpringSmooth(hikeTitleAlpha, hikeTitleAlphaTarget, ref hikeTitleAlphaSpeed, 0.4f, Time.deltaTime); labsTitleAlpha = Smoothing.SpringSmooth(labsTitleAlpha, labsTitleAlphaTarget, ref labsTitleAlphaSpeed, 0.4f, Time.deltaTime); Color col = labTitle.color; col.a = labsTitleAlpha; labTitle.color = col; col = hikeTitle.color; col.a = hikeTitleAlpha; hikeTitle.color = col; col = labIcon.material.color; col.a = labsTitleAlpha; labIcon.material.color = col; col = hikeIcon.material.color; col.a = hikeTitleAlpha; hikeIcon.material.color = col; if (hikeMenu.gameObject.activeSelf) { if (mode != MenuMode.Hike && -hikeTitleAlpha < 0) { hikeMenu.gameObject.SetActive(false); } else { for (int i = 0; i < hikeListItems.Length; i++) { col = hikeListItems[i].material.color; col.a = Mathf.Clamp01(-hikeTitleAlpha); hikeListItems[i].material.color = col; } } hike1.PlateAlpha = Mathf.Clamp01(-hikeTitleAlpha); hike2.PlateAlpha = Mathf.Clamp01(-hikeTitleAlpha); hike3.PlateAlpha = Mathf.Clamp01(-hikeTitleAlpha); hike4.PlateAlpha = Mathf.Clamp01(-hikeTitleAlpha); hike5.PlateAlpha = Mathf.Clamp01(-hikeTitleAlpha); } if (menu.gameObject.activeSelf) { if (mode != MenuMode.Labs && -labsTitleAlpha < 0) { menu.gameObject.SetActive(false); } else { for (int i = 0; i < labsListItems.Length; i++) { col = labsListItems[i].material.color; col.a = Mathf.Clamp01(-labsTitleAlpha); labsListItems[i].material.color = col; } } motion.PlateAlpha = Mathf.Clamp01(-labsTitleAlpha); targeting.PlateAlpha = Mathf.Clamp01(-labsTitleAlpha); tracking.PlateAlpha = Mathf.Clamp01(-labsTitleAlpha); text.PlateAlpha = Mathf.Clamp01(-labsTitleAlpha); relativity.PlateAlpha = Mathf.Clamp01(-labsTitleAlpha); } if (fadeValue != targetFade) { fadeValue = Smoothing.SpringSmooth(fadeValue, targetFade, ref fadeSpeed, spring, Time.deltaTime); ResetUIColor(); if (fadeValue > 0) { for (int i = 0; i < labsRenderers.Length; i++) { labsRenderers[i].enabled = true; Color c = labsRenderers[i].material.color; c.a = fadeValue; labsRenderers[i].material.color = c; } for (int i = 0; i < redwoodsRenderers.Length; i++) { if (redwoodsRenderers[i] != null) { redwoodsRenderers[i].enabled = false; //Color c = redwoodsRenderers[i].material.color; //c.a = 0; //redwoodsRenderers[i].material.color = c; } } } else if (fadeValue < 0) { for (int i = 0; i < labsRenderers.Length; i++) { labsRenderers[i].enabled = false; //Color c = labsRenderers[i].material.color; //c.a = 0; //labsRenderers[i].material.color = c; } for (int i = 0; i < redwoodsRenderers.Length; i++) { if (redwoodsRenderers[i] != null) { redwoodsRenderers[i].enabled = true; Color c = redwoodsRenderers[i].material.color; c.a = -fadeValue; redwoodsRenderers[i].material.color = c; } } } else { for (int i = 0; i < labsRenderers.Length; i++) { labsRenderers[i].enabled = false; } for (int i = 0; i < redwoodsRenderers.Length; i++) { if (redwoodsRenderers[i] != null) { redwoodsRenderers[i].enabled = false; } } } } //// If the user rotates the screen too far away from the sub-menu, fade back to the splash screen if (Mathf.Abs(Mathf.DeltaAngle(OrientationYaw, VRInput.Instance.Yaw)) > 50) { MainMenu(); SceneManager.Instance.StateTransition(SceneManager.Instance.splashScene); } if (Mathf.Abs(Mathf.DeltaAngle(0, VRInput.Instance.Pitch)) > 35) { MainMenu(); SceneManager.Instance.StateTransition(SceneManager.Instance.splashScene); } }
/// Internal contructor VertexPath(BezierPath bezierPath, VertexPathUtility.PathSplitData pathSplitData) { space = bezierPath.Space; isClosedLoop = bezierPath.IsClosed; int numVerts = pathSplitData.vertices.Count; length = pathSplitData.cumulativeLength[numVerts - 1]; vertices = new Vector3[numVerts]; normals = new Vector3[numVerts]; tangents = new Vector3[numVerts]; cumulativeLengthAtEachVertex = new float[numVerts]; times = new float[numVerts]; bounds = new Bounds((pathSplitData.minMax.Min + pathSplitData.minMax.Max) / 2, pathSplitData.minMax.Max - pathSplitData.minMax.Min); // Figure out up direction for path up = (bounds.size.z > bounds.size.y) ? Vector3.up : -Vector3.forward; Vector3 lastRotationAxis = up; // Loop through the data and assign to arrays. for (int i = 0; i < vertices.Length; i++) { vertices[i] = pathSplitData.vertices[i]; tangents[i] = pathSplitData.tangents[i]; cumulativeLengthAtEachVertex[i] = pathSplitData.cumulativeLength[i]; times[i] = cumulativeLengthAtEachVertex[i] / length; // Calculate normals if (space == PathSpace.xyz) { if (i == 0) { normals[0] = Vector3.Cross(lastRotationAxis, pathSplitData.tangents[0]).normalized; } else { // First reflection Vector3 offset = (vertices[i] - vertices[i - 1]); float sqrDst = offset.sqrMagnitude; Vector3 r = lastRotationAxis - offset * 2 / sqrDst * Vector3.Dot(offset, lastRotationAxis); Vector3 t = tangents[i - 1] - offset * 2 / sqrDst * Vector3.Dot(offset, tangents[i - 1]); // Second reflection Vector3 v2 = tangents[i] - t; float c2 = Vector3.Dot(v2, v2); Vector3 finalRot = r - v2 * 2 / c2 * Vector3.Dot(v2, r); Vector3 n = Vector3.Cross(finalRot, tangents[i]).normalized; normals[i] = n; lastRotationAxis = finalRot; } } else { normals[i] = Vector3.Cross(tangents[i], up) * ((bezierPath.FlipNormals) ? 1 : -1); } } // Apply correction for 3d normals along a closed path if (space == PathSpace.xyz && isClosedLoop) { // Get angle between first and last normal (if zero, they're already lined up, otherwise we need to correct) float normalsAngleErrorAcrossJoin = Vector3.SignedAngle(normals[normals.Length - 1], normals[0], tangents[0]); // Gradually rotate the normals along the path to ensure start and end normals line up correctly if (Mathf.Abs(normalsAngleErrorAcrossJoin) > 0.1f) // don't bother correcting if very nearly correct { for (int i = 1; i < normals.Length; i++) { float t = (i / (normals.Length - 1f)); float angle = normalsAngleErrorAcrossJoin * t; Quaternion rot = Quaternion.AngleAxis(angle, tangents[i]); normals[i] = rot * normals[i] * ((bezierPath.FlipNormals) ? -1 : 1); } } } // Rotate normals to match up with user-defined anchor angles if (space == PathSpace.xyz) { for (int anchorIndex = 0; anchorIndex < pathSplitData.anchorVertexMap.Count - 1; anchorIndex++) { int nextAnchorIndex = (isClosedLoop) ? (anchorIndex + 1) % bezierPath.NumSegments : anchorIndex + 1; float startAngle = bezierPath.GetAnchorNormalAngle(anchorIndex) + bezierPath.GlobalNormalsAngle; float endAngle = bezierPath.GetAnchorNormalAngle(nextAnchorIndex) + bezierPath.GlobalNormalsAngle; float deltaAngle = Mathf.DeltaAngle(startAngle, endAngle); int startVertIndex = pathSplitData.anchorVertexMap[anchorIndex]; int endVertIndex = pathSplitData.anchorVertexMap[anchorIndex + 1]; int num = endVertIndex - startVertIndex; if (anchorIndex == pathSplitData.anchorVertexMap.Count - 2) { num += 1; } for (int i = 0; i < num; i++) { int vertIndex = startVertIndex + i; float t = i / (num - 1f); float angle = startAngle + deltaAngle * t; Quaternion rot = Quaternion.AngleAxis(angle, tangents[vertIndex]); normals[vertIndex] = (rot * normals[vertIndex]) * ((bezierPath.FlipNormals) ? -1 : 1); } } } }
public void Update() { this.healthTime -= Time.deltaTime; UpdateLabel(); if (this.state == "null") { return; } if (this.state == "wait") { this.waitTime -= Time.deltaTime; if (this.waitTime <= 0f) { baseT.position = new Vector3(30f, 0f, 784f); //UnityEngine.Object.Instantiate(CacheResources.Load("FX/ThunderCT"), baseT.position + Vectors.up * 350f, Quaternion.Euler(270f, 0f, 0f)); Pool.Enable("FX/ThunderCT", baseT.position + Vectors.up * 350f, Quaternion.Euler(270f, 0f, 0f)); IN_GAME_MAIN_CAMERA.MainCamera.flashBlind(); if (IN_GAME_MAIN_CAMERA.GameType == GameType.Single) { this.idle(); } else if ((!FengGameManagerMKII.LAN) ? BasePV.IsMine : base.networkView.isMine) { this.idle(); } else { this.state = "null"; } } } else { if (this.state == "idle") { if (this.attackPattern == -1) { this.slap("r1"); this.attackPattern++; } else if (this.attackPattern == 0) { this.attack_sweep(string.Empty); this.attackPattern++; } else if (this.attackPattern == 1) { this.steam(); this.attackPattern++; } else if (this.attackPattern == 2) { this.kick(); this.attackPattern++; } else { if (this.isSteamNeed || this.hasDie) { this.steam(); this.isSteamNeed = false; return; } if (this.myHero == null) { this.findNearestHero(); } else { Vector3 vector = this.myHero.transform.position - baseT.position; float current = -Mathf.Atan2(vector.z, vector.x) * 57.29578f; float f = -Mathf.DeltaAngle(current, baseGT.rotation.eulerAngles.y - 90f); this.myDistance = Mathf.Sqrt((this.myHero.transform.position.x - baseT.position.x) * (this.myHero.transform.position.x - baseT.position.x) + (this.myHero.transform.position.z - baseT.position.z) * (this.myHero.transform.position.z - baseT.position.z)); float num = this.myHero.transform.position.y - baseT.position.y; if (this.myDistance < 85f && UnityEngine.Random.Range(0, 100) < 5) { this.steam(); return; } if (num > 310f && num < 350f) { if (Vector3.Distance(this.myHero.transform.position, baseT.Find("APL1").position) < 40f) { this.slap("l1"); return; } if (Vector3.Distance(this.myHero.transform.position, baseT.Find("APL2").position) < 40f) { this.slap("l2"); return; } if (Vector3.Distance(this.myHero.transform.position, baseT.Find("APR1").position) < 40f) { this.slap("r1"); return; } if (Vector3.Distance(this.myHero.transform.position, baseT.Find("APR2").position) < 40f) { this.slap("r2"); return; } if (this.myDistance < 150f && Mathf.Abs(f) < 80f) { this.attack_sweep(string.Empty); return; } } if (num < 300f && Mathf.Abs(f) < 80f && this.myDistance < 85f) { this.attack_sweep("_vertical"); return; } int num2 = UnityEngine.Random.Range(0, 7); if (num2 == 0) { this.slap("l1"); } else if (num2 == 1) { this.slap("l2"); } else if (num2 == 2) { this.slap("r1"); } else if (num2 == 3) { this.slap("r2"); } else if (num2 == 4) { this.attack_sweep(string.Empty); } else if (num2 == 5) { this.attack_sweep("_vertical"); } else if (num2 == 6) { this.steam(); } } } return; } if (this.state == "attack_sweep") { if (this.attackCheckTimeA != 0f && ((base.animation["attack_" + this.attackAnimation].normalizedTime >= this.attackCheckTimeA && base.animation["attack_" + this.attackAnimation].normalizedTime <= this.attackCheckTimeB) || (!this.attackChkOnce && base.animation["attack_" + this.attackAnimation].normalizedTime >= this.attackCheckTimeA))) { if (!this.attackChkOnce) { this.attackChkOnce = true; } foreach (RaycastHit raycastHit in this.checkHitCapsule(this.checkHitCapsuleStart.position, this.checkHitCapsuleEnd.position, this.checkHitCapsuleR)) { GameObject gameObject = raycastHit.collider.gameObject; if (gameObject.CompareTag("Player")) { this.killPlayer(gameObject); } if (gameObject.CompareTag("erenHitbox") && this.attackAnimation == "combo_3" && IN_GAME_MAIN_CAMERA.GameType == GameType.MultiPlayer && ((!FengGameManagerMKII.LAN) ? PhotonNetwork.IsMasterClient : Network.isServer)) { gameObject.transform.root.gameObject.GetComponent <TITAN_EREN>().hitByFTByServer(3); } } foreach (RaycastHit raycastHit2 in this.checkHitCapsule(this.checkHitCapsuleEndOld, this.checkHitCapsuleEnd.position, this.checkHitCapsuleR)) { GameObject gameObject2 = raycastHit2.collider.gameObject; if (gameObject2.CompareTag("Player")) { this.killPlayer(gameObject2); } } this.checkHitCapsuleEndOld = this.checkHitCapsuleEnd.position; } if (base.animation["attack_" + this.attackAnimation].normalizedTime >= 1f) { this.sweepSmokeObject.GetComponent <ParticleSystem>().enableEmission = false; this.sweepSmokeObject.GetComponent <ParticleSystem>().Stop(); if (IN_GAME_MAIN_CAMERA.GameType == GameType.MultiPlayer) { if (!FengGameManagerMKII.LAN) { BasePV.RPC("stopSweepSmoke", PhotonTargets.Others, new object[0]); } } this.findNearestHero(); this.idle(); this.playAnimation("idle"); } } else if (this.state == "kick") { if (!this.attackChkOnce && base.animation[this.actionName].normalizedTime >= this.attackCheckTime) { this.attackChkOnce = true; this.door_broken.SetActive(true); this.door_closed.SetActive(false); if (IN_GAME_MAIN_CAMERA.GameType == GameType.MultiPlayer) { if (!FengGameManagerMKII.LAN) { BasePV.RPC("changeDoor", PhotonTargets.OthersBuffered, new object[0]); } } if (IN_GAME_MAIN_CAMERA.GameType == GameType.MultiPlayer) { if (FengGameManagerMKII.LAN) { Network.Instantiate(CacheResources.Load("FX/boom1_CT_KICK"), baseT.position + baseT.Forward() * 120f + baseT.right * 30f, Quaternion.Euler(270f, 0f, 0f), 0); Network.Instantiate(CacheResources.Load("rock"), baseT.position + baseT.Forward() * 120f + baseT.right * 30f, Quaternion.Euler(0f, 0f, 0f), 0); } else { Optimization.Caching.Pool.NetworkEnable("FX/boom1_CT_KICK", baseT.position + baseT.Forward() * 120f + baseT.right * 30f, Quaternion.Euler(270f, 0f, 0f), 0); Optimization.Caching.Pool.NetworkEnable("rock", baseT.position + baseT.Forward() * 120f + baseT.right * 30f, Quaternion.Euler(0f, 0f, 0f), 0); } } else { Pool.Enable("FX/boom1_CT_KICK", baseT.position + baseT.Forward() * 120f + baseT.right * 30f, Quaternion.Euler(270f, 0f, 0f)); //UnityEngine.Object.Instantiate(CacheResources.Load("FX/boom1_CT_KICK"), baseT.position + baseT.Forward() * 120f + baseT.right * 30f, Quaternion.Euler(270f, 0f, 0f)); Pool.Enable("rock", baseT.position + baseT.Forward() * 120f + baseT.right * 30f, Quaternion.Euler(0f, 0f, 0f)); } } if (base.animation[this.actionName].normalizedTime >= 1f) { this.findNearestHero(); this.idle(); this.playAnimation("idle"); } } else if (this.state == "slap") { if (!this.attackChkOnce && base.animation["attack_slap_" + this.attackAnimation].normalizedTime >= this.attackCheckTime) { this.attackChkOnce = true; GameObject gameObject3; if (IN_GAME_MAIN_CAMERA.GameType == GameType.MultiPlayer) { if (FengGameManagerMKII.LAN) { gameObject3 = (GameObject)Network.Instantiate(CacheResources.Load("FX/boom1"), this.checkHitCapsuleStart.position, Quaternion.Euler(270f, 0f, 0f), 0); } else { gameObject3 = Optimization.Caching.Pool.NetworkEnable("FX/boom1", this.checkHitCapsuleStart.position, Quaternion.Euler(270f, 0f, 0f), 0); } if (gameObject3.GetComponent <EnemyfxIDcontainer>()) { gameObject3.GetComponent <EnemyfxIDcontainer>().titanName = base.name; } } else { gameObject3 = Pool.Enable("FX/boom1", this.checkHitCapsuleStart.position, Quaternion.Euler(270f, 0f, 0f));//(GameObject)UnityEngine.Object.Instantiate(CacheResources.Load("FX/boom1"), this.checkHitCapsuleStart.position, Quaternion.Euler(270f, 0f, 0f)); } gameObject3.transform.localScale = new Vector3(5f, 5f, 5f); } if (base.animation["attack_slap_" + this.attackAnimation].normalizedTime >= 1f) { this.findNearestHero(); this.idle(); this.playAnimation("idle"); } } else if (this.state == "steam") { if (!this.attackChkOnce && base.animation[this.actionName].normalizedTime >= this.attackCheckTime) { this.attackChkOnce = true; if (IN_GAME_MAIN_CAMERA.GameType == GameType.MultiPlayer) { if (FengGameManagerMKII.LAN) { Network.Instantiate(CacheResources.Load("FX/colossal_steam"), baseT.position + baseT.Up() * 185f, Quaternion.Euler(270f, 0f, 0f), 0); Network.Instantiate(CacheResources.Load("FX/colossal_steam"), baseT.position + baseT.Up() * 303f, Quaternion.Euler(270f, 0f, 0f), 0); Network.Instantiate(CacheResources.Load("FX/colossal_steam"), baseT.position + baseT.Up() * 50f, Quaternion.Euler(270f, 0f, 0f), 0); } else { Optimization.Caching.Pool.NetworkEnable("FX/colossal_steam", baseT.position + baseT.Up() * 185f, Quaternion.Euler(270f, 0f, 0f), 0); Optimization.Caching.Pool.NetworkEnable("FX/colossal_steam", baseT.position + baseT.Up() * 303f, Quaternion.Euler(270f, 0f, 0f), 0); Optimization.Caching.Pool.NetworkEnable("FX/colossal_steam", baseT.position + baseT.Up() * 50f, Quaternion.Euler(270f, 0f, 0f), 0); } } else { Pool.Enable("FX/colossal_steam", baseT.position + baseT.Forward() * 185f, Quaternion.Euler(270f, 0f, 0f)); Pool.Enable("FX/colossal_steam", baseT.position + baseT.Forward() * 303f, Quaternion.Euler(270f, 0f, 0f)); Pool.Enable("FX/colossal_steam", baseT.position + baseT.Forward() * 50f, Quaternion.Euler(270f, 0f, 0f)); //UnityEngine.Object.Instantiate(CacheResources.Load("FX/colossal_steam"), baseT.position + baseT.Forward() * 185f, Quaternion.Euler(270f, 0f, 0f)); //UnityEngine.Object.Instantiate(CacheResources.Load("FX/colossal_steam"), baseT.position + baseT.Forward() * 303f, Quaternion.Euler(270f, 0f, 0f)); //UnityEngine.Object.Instantiate(CacheResources.Load("FX/colossal_steam"), baseT.position + baseT.Forward() * 50f, Quaternion.Euler(270f, 0f, 0f)); } } if (base.animation[this.actionName].normalizedTime >= 1f) { if (IN_GAME_MAIN_CAMERA.GameType == GameType.MultiPlayer) { if (FengGameManagerMKII.LAN) { Network.Instantiate(CacheResources.Load("FX/colossal_steam_dmg"), baseT.position + baseT.Up() * 185f, Quaternion.Euler(270f, 0f, 0f), 0); Network.Instantiate(CacheResources.Load("FX/colossal_steam_dmg"), baseT.position + baseT.Up() * 303f, Quaternion.Euler(270f, 0f, 0f), 0); Network.Instantiate(CacheResources.Load("FX/colossal_steam_dmg"), baseT.position + baseT.Up() * 50f, Quaternion.Euler(270f, 0f, 0f), 0); } else { GameObject gameObject4 = Optimization.Caching.Pool.NetworkEnable("FX/colossal_steam_dmg", baseT.position + baseT.Up() * 185f, Quaternion.Euler(270f, 0f, 0f), 0); if (gameObject4.GetComponent <EnemyfxIDcontainer>()) { gameObject4.GetComponent <EnemyfxIDcontainer>().titanName = base.name; } gameObject4 = Optimization.Caching.Pool.NetworkEnable("FX/colossal_steam_dmg", baseT.position + baseT.Up() * 303f, Quaternion.Euler(270f, 0f, 0f), 0); if (gameObject4.GetComponent <EnemyfxIDcontainer>()) { gameObject4.GetComponent <EnemyfxIDcontainer>().titanName = base.name; } gameObject4 = Optimization.Caching.Pool.NetworkEnable("FX/colossal_steam_dmg", baseT.position + baseT.Up() * 50f, Quaternion.Euler(270f, 0f, 0f), 0); if (gameObject4.GetComponent <EnemyfxIDcontainer>()) { gameObject4.GetComponent <EnemyfxIDcontainer>().titanName = base.name; } } } else { Pool.Enable("FX/colossal_steam_dmg", baseT.position + baseT.Forward() * 185f, Quaternion.Euler(270f, 0f, 0f)); Pool.Enable("FX/colossal_steam_dmg", baseT.position + baseT.Forward() * 303f, Quaternion.Euler(270f, 0f, 0f)); Pool.Enable("FX/colossal_steam_dmg", baseT.position + baseT.Forward() * 50f, Quaternion.Euler(270f, 0f, 0f)); //UnityEngine.Object.Instantiate(CacheResources.Load("FX/colossal_steam_dmg"), baseT.position + baseT.Forward() * 185f, Quaternion.Euler(270f, 0f, 0f)); //UnityEngine.Object.Instantiate(CacheResources.Load("FX/colossal_steam_dmg"), baseT.position + baseT.Forward() * 303f, Quaternion.Euler(270f, 0f, 0f)); //UnityEngine.Object.Instantiate(CacheResources.Load("FX/colossal_steam_dmg"), baseT.position + baseT.Forward() * 50f, Quaternion.Euler(270f, 0f, 0f)); } if (this.hasDie) { if (IN_GAME_MAIN_CAMERA.GameType == GameType.Single) { UnityEngine.Object.Destroy(baseG); } else if (FengGameManagerMKII.LAN) { if (base.networkView.isMine) { } } else if (PhotonNetwork.IsMasterClient) { PhotonNetwork.Destroy(BasePV); } FengGameManagerMKII.FGM.GameWin(); } this.findNearestHero(); this.idle(); this.playAnimation("idle"); } } else if (this.state == string.Empty) { } } }
public void DrawHandle() { if (!this.m_ControlIDsReserved) { this.GetControlIDs(); } this.m_ControlIDsReserved = false; if (Handles.color.a != 0f) { Vector3 vector = Handles.matrix.MultiplyPoint3x4(Vector3.one) - Handles.matrix.MultiplyPoint3x4(Vector3.zero); if (vector.x != 0f || vector.z != 0f) { Vector3 vector2 = Quaternion.AngleAxis(this.angle, Vector3.up) * Vector3.forward * this.radius; float num = Mathf.Abs(this.angle); float num2 = this.angle % 360f; using (new Handles.DrawingScope(Handles.color * this.fillColor)) { if (Handles.color.a > 0f) { int i = 0; int num3 = (int)num / 360; while (i < num3) { Handles.DrawSolidArc(Vector3.zero, Vector3.up, Vector3.forward, 360f, this.radius); i++; } Handles.DrawSolidArc(Vector3.zero, Vector3.up, Vector3.forward, num2, this.radius); } } using (new Handles.DrawingScope(Handles.color * this.wireframeColor)) { if (Handles.color.a > 0f) { Handles.DrawWireArc(Vector3.zero, Vector3.up, Vector3.forward, (num < 360f) ? num2 : 360f, this.radius); } } if (Event.current.alt) { bool flag = true; int[] radiusHandleControlIDs = this.m_RadiusHandleControlIDs; for (int j = 0; j < radiusHandleControlIDs.Length; j++) { int num4 = radiusHandleControlIDs[j]; if (num4 == GUIUtility.hotControl) { flag = false; break; } } if (flag && GUIUtility.hotControl != this.m_AngleHandleControlID) { return; } } using (new Handles.DrawingScope(Handles.color * this.radiusHandleColor)) { if (Handles.color.a > 0f) { float num5 = Mathf.Sign(this.angle); int num6 = Mathf.Min(1 + (int)(Mathf.Min(360f, num) * 0.0111111114f), 4); for (int k = 0; k < num6; k++) { Quaternion q = Quaternion.AngleAxis((float)k * 90f * num5, Vector3.up); using (new Handles.DrawingScope(Handles.matrix * Matrix4x4.TRS(Vector3.zero, q, Vector3.one))) { Vector3 vector3 = Vector3.forward * this.radius; EditorGUI.BeginChangeCheck(); float num7 = (this.radiusHandleSizeFunction != null) ? this.radiusHandleSizeFunction(vector3) : ArcHandle.DefaultRadiusHandleSizeFunction(vector3); int arg_37A_0 = this.m_RadiusHandleControlIDs[k]; Vector3 arg_37A_1 = vector3; Vector3 arg_37A_2 = Vector3.forward; float arg_37A_3 = num7; Handles.CapFunction arg_37A_4; if ((arg_37A_4 = this.radiusHandleDrawFunction) == null) { if (ArcHandle.< > f__mg$cache0 == null) { ArcHandle.< > f__mg$cache0 = new Handles.CapFunction(ArcHandle.DefaultRadiusHandleDrawFunction); } arg_37A_4 = ArcHandle.< > f__mg$cache0; } Vector3 a = Handles.Slider(arg_37A_0, arg_37A_1, arg_37A_2, arg_37A_3, arg_37A_4, SnapSettings.move.z); if (EditorGUI.EndChangeCheck()) { this.radius += (a - vector3).z; } } } } } using (new Handles.DrawingScope(Handles.color * this.angleHandleColor)) { if (Handles.color.a > 0f) { EditorGUI.BeginChangeCheck(); float handleSize = (this.angleHandleSizeFunction != null) ? this.angleHandleSizeFunction(vector2) : ArcHandle.DefaultAngleHandleSizeFunction(vector2); vector2 = Handles.Slider2D(this.m_AngleHandleControlID, vector2, Vector3.up, Vector3.forward, Vector3.right, handleSize, this.angleHandleDrawFunction ?? new Handles.CapFunction(this.DefaultAngleHandleDrawFunction), Vector2.zero); if (EditorGUI.EndChangeCheck()) { float target = Vector3.Angle(Vector3.forward, vector2) * Mathf.Sign(Vector3.Dot(Vector3.right, vector2)); this.angle += Mathf.DeltaAngle(this.angle, target); this.angle = Handles.SnapValue(this.angle, SnapSettings.rotation); } } } } } }
// Rotating bone to get transform aim closer to target private void RotateToTarget(UnityEngine.Animations.AnimationStream s, Vector3 targetPosition, Vector3 polePosition, int i, float weight, float poleWeight, bool XY, bool useRotationLimits, Vector3 axis, Vector3 poleAxis) { // Swing if (XY) { if (weight >= 0f) { Vector3 dir = _transform.GetRotation(s) * axis; Vector3 targetDir = targetPosition - _transform.GetPosition(s); float angleDir = Mathf.Atan2(dir.x, dir.y) * Mathf.Rad2Deg; float angleTarget = Mathf.Atan2(targetDir.x, targetDir.y) * Mathf.Rad2Deg; bones[i].SetRotation(s, Quaternion.AngleAxis(Mathf.DeltaAngle(angleDir, angleTarget), Vector3.back) * bones[i].GetRotation(s)); } } else { if (weight >= 0f) { Quaternion rotationOffset = Quaternion.FromToRotation(_transform.GetRotation(s) * axis, targetPosition - _transform.GetPosition(s)); if (weight >= 1f) { bones[i].SetRotation(s, rotationOffset * bones[i].GetRotation(s)); } else { bones[i].SetRotation(s, Quaternion.Lerp(Quaternion.identity, rotationOffset, weight) * bones[i].GetRotation(s)); } } // Pole if (poleWeight > 0f) { Vector3 poleDirection = polePosition - _transform.GetPosition(s); // Ortho-normalize to transform axis to make this a twisting only operation Vector3 poleDirOrtho = poleDirection; Vector3 normal = _transform.GetRotation(s) * axis; Vector3.OrthoNormalize(ref normal, ref poleDirOrtho); Quaternion toPole = Quaternion.FromToRotation(_transform.GetRotation(s) * poleAxis, poleDirOrtho); bones[i].SetRotation(s, Quaternion.Lerp(Quaternion.identity, toPole, weight * poleWeight) * bones[i].GetRotation(s)); } } // Rotation Constraints if (useRotationLimits) { if (hingeFlags[i] == 1) { Quaternion localRotation = Quaternion.Inverse(limitDefaultLocalRotationArray[i]) * bones[i].GetLocalRotation(s); Quaternion lastRotation = hingeLastRotations[i]; float lastAngle = hingeLastAngles[i]; Quaternion r = RotationLimitUtilities.LimitHinge(localRotation, hingeMinArray[i].GetFloat(s), hingeMaxArray[i].GetFloat(s), hingeUseLimitsArray[i].GetBool(s), limitAxisArray[i], ref lastRotation, ref lastAngle); hingeLastRotations[i] = lastRotation; hingeLastAngles[i] = lastAngle; bones[i].SetLocalRotation(s, limitDefaultLocalRotationArray[i] * r); } else if (angleFlags[i] == 1) { Quaternion localRotation = Quaternion.Inverse(limitDefaultLocalRotationArray[i]) * bones[i].GetLocalRotation(s); Quaternion r = RotationLimitUtilities.LimitAngle(localRotation, limitAxisArray[i], angleSecondaryAxisArray[i], angleLimitArray[i].GetFloat(s), angleTwistLimitArray[i].GetFloat(s)); bones[i].SetLocalRotation(s, limitDefaultLocalRotationArray[i] * r); } } }
private float calculateAngleDistance(float current, float target) { return(Mathf.Abs(Mathf.DeltaAngle(current, target))); }
public bool CloseEnoughToDediredAngle(Transform transform, float minAngleDifference = 0.0f) { return(Mathf.Abs(Mathf.DeltaAngle(transform.rotation.eulerAngles.z, desiredAngle)) < minAngleDifference); }
void fire() { float dist = 0; var aimRay = Camera.main.ScreenPointToRay(Input.mousePosition); if (mouseCastPlane.Raycast(aimRay, out dist)) { Vector2 aimPivotPos = aimPivotBone.transform.position; Vector2 targetPos = aimRay.GetPoint(dist); aimStick = (targetPos - aimPivotPos).normalized; } if (a < 0) { a += 360; } if (a < 270 && a > 90) { flip = true; } else { flip = false; } flipped = flip; mouse = Camera.main.ScreenToWorldPoint(Input.mousePosition); angle = Mathf.Atan2(mouse.y - target.y, mouse.x - target.x) * Mathf.Rad2Deg; a = Mathf.Atan2(aimStick.y, aimStick.x) * Mathf.Rad2Deg; b = Mathf.Atan2(aimStick.y, aimStick.x) * Mathf.Rad2Deg; a = flip ? 180 + Mathf.Clamp(Mathf.DeltaAngle(0, a - 180), -maxAngle, -minAngle) : Mathf.Clamp(Mathf.DeltaAngle(0, a), minAngle, maxAngle); b = flip ? 180 + Mathf.Clamp(Mathf.DeltaAngle(0, b - 180), -maxAngle, -minAngle) : Mathf.Clamp(Mathf.DeltaAngle(0, b), minAngle, maxAngle); aimPivotBone.transform.localRotation = Quaternion.RotateTowards(aimPivotBone.transform.localRotation, Quaternion.AngleAxis(flip ? 180 - a : a, Vector3.forward), 1000 * Time.deltaTime); vec = Quaternion.RotateTowards(vec, Quaternion.AngleAxis(flip ? 180 + b : b, Vector3.forward), 10000 * Time.deltaTime); }
/// <summary> /// When in slave mode, this should be called once and only /// once every hrame to update the heading. When not in slave mode, this is called automatically. /// </summary> public void UpdateHeading(float deltaTime, Vector3 up) { // Only read joystick when game is playing if (deltaTime >= 0 || CinemachineCore.Instance.IsLive(VirtualCamera)) { bool xAxisInput = m_XAxis.Update(deltaTime); if (xAxisInput) { mLastHeadingAxisInputTime = Time.time; mHeadingRecenteringVelocity = 0; } } float targetHeading = GetTargetHeading(m_XAxis.Value, GetReferenceOrientation(up), deltaTime); if (deltaTime < 0) { mHeadingRecenteringVelocity = 0; if (m_RecenterToTargetHeading.m_enabled) { m_XAxis.Value = targetHeading; } } else { // Recentering if (m_BindingMode != BindingMode.SimpleFollowWithWorldUp && m_RecenterToTargetHeading.m_enabled && (Time.time > (mLastHeadingAxisInputTime + m_RecenterToTargetHeading.m_RecenterWaitTime))) { // Scale value determined heuristically, to account for accel/decel float recenterTime = m_RecenterToTargetHeading.m_RecenteringTime / 3f; if (recenterTime <= deltaTime) { m_XAxis.Value = targetHeading; } else { float headingError = Mathf.DeltaAngle(m_XAxis.Value, targetHeading); float absHeadingError = Mathf.Abs(headingError); if (absHeadingError < UnityVectorExtensions.Epsilon) { m_XAxis.Value = targetHeading; mHeadingRecenteringVelocity = 0; } else { float scale = deltaTime / recenterTime; float desiredVelocity = Mathf.Sign(headingError) * Mathf.Min(absHeadingError, absHeadingError * scale); // Accelerate to the desired velocity float accel = desiredVelocity - mHeadingRecenteringVelocity; if ((desiredVelocity < 0 && accel < 0) || (desiredVelocity > 0 && accel > 0)) { desiredVelocity = mHeadingRecenteringVelocity + desiredVelocity * scale; } m_XAxis.Value += desiredVelocity; mHeadingRecenteringVelocity = desiredVelocity; } } } } }
void HandleMovement() { HandleEditorInput(); // Look input yaw += Input.GetAxisRaw("Mouse X") * mouseSensitivity; pitch -= Input.GetAxisRaw("Mouse Y") * mouseSensitivity; pitch = Mathf.Clamp(pitch - Input.GetAxisRaw("Mouse Y") * mouseSensitivity, pitchMinMax.x, pitchMinMax.y); smoothPitch = Mathf.SmoothDampAngle(smoothPitch, pitch, ref pitchSmoothV, rotationSmoothTime); float smoothYawOld = smoothYaw; smoothYaw = Mathf.SmoothDampAngle(smoothYaw, yaw, ref yawSmoothV, rotationSmoothTime); if (!debug_playerFrozen) { cam.transform.localEulerAngles = Vector3.right * smoothPitch; transform.Rotate(Vector3.up * Mathf.DeltaAngle(smoothYawOld, smoothYaw), Space.Self); } // Movement bool isGrounded = IsGrounded(); Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")); bool running = Input.GetKey(KeyCode.LeftShift); targetVelocity = transform.TransformDirection(input.normalized) * ((running) ? runSpeed : walkSpeed); smoothVelocity = Vector3.SmoothDamp(smoothVelocity, targetVelocity, ref smoothVRef, (isGrounded) ? vSmoothTime : airSmoothTime); //bool inWater = referenceBody if (isGrounded) { if (Input.GetKeyDown(KeyCode.Space)) { rb.AddForce(transform.up * jumpForce, ForceMode.VelocityChange); isGrounded = false; } else { // Apply small downward force to prevent player from bouncing when going down slopes rb.AddForce(-transform.up * stickToGroundForce, ForceMode.VelocityChange); } } else { // Press (and hold) spacebar while above ground to engage jetpack if (Input.GetKeyDown(KeyCode.Space)) { usingJetpack = true; } } if (usingJetpack && Input.GetKey(KeyCode.Space) && jetpackFuelPercent > 0) { lastJetpackUseTime = Time.time; jetpackFuelPercent -= Time.deltaTime / jetpackDuration; rb.AddForce(transform.up * jetpackForce, ForceMode.Acceleration); } else { usingJetpack = false; } // Refuel jetpack if (Time.time - lastJetpackUseTime > jetpackRefuelDelay) { jetpackFuelPercent = Mathf.Clamp01(jetpackFuelPercent + Time.deltaTime / jetpackRefuelTime); } // Handle animations float currentSpeed = smoothVelocity.magnitude; float animationSpeedPercent = (currentSpeed <= walkSpeed) ? currentSpeed / walkSpeed / 2 : currentSpeed / runSpeed; animator.SetBool("Grounded", isGrounded); animator.SetFloat("Speed", animationSpeedPercent); }
void move() { if (hitpoint <= 0) { return; } float v = Input.GetAxis("Vertical"); float h = Input.GetAxis("Horizontal"); Vector3 vec = Vector3.ClampMagnitude(new Vector3(h, 0, v), 1f); Quaternion q = Quaternion.Euler(0, Camera.main.transform.rotation.eulerAngles.y, 0); vec = q * vec; //anim.applyRootMotion=false; if (vec.magnitude > 0f) { float nowRot = transform.rotation.eulerAngles.y; float targetRot = Mathf.Atan2(vec.x, vec.z) * Mathf.Rad2Deg; float targetRotOrg = targetRot; float deltaRot = Mathf.Abs(Mathf.DeltaAngle(nowRot, targetRot)); float rspeed = rotSpeed * Time.deltaTime; if (deltaRot > rspeed) { targetRot = Mathf.LerpAngle(nowRot, targetRot, rspeed / deltaRot); } transform.rotation = Quaternion.Euler(0, targetRotOrg, 0); float dir = Mathf.DeltaAngle(nowRot, targetRotOrg) / dirRatio; } float speed = vec.magnitude; Vector3 move = transform.forward * speed; if (Mathf.Abs(speed) >= 0f) { if (time >= 2) { anim.SetFloat("speed", speed * 2); move *= runSpeed; } else { anim.SetFloat("speed", speed); move *= walkSpeed; time += Time.deltaTime; } } if (Mathf.Abs(speed) <= 0.05f) { speed = 0; time = 0; } move.y = rbody.velocity.y; rbody.velocity = move; if (state == State.idle) { if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.Joystick1Button0)) { if (isAttack == false) { jumpNum++; } } } jump(); }
/// <summary> /// Objectの回転 /// </summary> Vector3 GetAngularVelocity() { Quaternion deltaRotation = currentRoation * Quaternion.Inverse(lastRootation); return(new Vector3(Mathf.DeltaAngle(0, deltaRotation.eulerAngles.x), Mathf.DeltaAngle(0, deltaRotation.eulerAngles.y), Mathf.DeltaAngle(0, deltaRotation.eulerAngles.z))); }
void Update() { if (Input.touchCount == 2) { Touch touch1 = Input.touches[0]; Touch touch2 = Input.touches[1]; Vector2 pos1 = touch1.position; Vector2 pos2 = touch2.position; Vector2 delta1 = pos1 - lastTouchPos1; Vector2 delta2 = pos2 - lastTouchPos2; if (firstTouch) { firstTouch = false; //for rotate initPos1 = pos1; initPos2 = pos2; initGradient = (pos1 - pos2).normalized; float curX = pos1.x - pos2.x; float curY = pos1.y - pos2.y; float prevAngle = Gesture.VectorToAngle(new Vector2(curX, curY)); //for tap tapStartTime = Time.time; startPos = (pos1 + pos2) / 2; longTap = false; posShifted = false; } else { if (Vector2.Distance(Input.mousePosition, startPos) > 5) { posShifted = true; } if (Time.time - tapStartTime > minChargeTime) { charged = true; float chargeValue = Mathf.Min(1, (Time.time - tapStartTime) / maxChargeTime); ChargedInfo cInfo = new ChargedInfo((pos1 + pos2) / 2, chargeValue); Gesture.DFCharging(cInfo); } if (!longTap && !posShifted && Time.time - tapStartTime > 1f) { longTap = true; Gesture.DFLongTap((pos1 + pos2) / 2); } } if (touch1.phase == TouchPhase.Moved && touch2.phase == TouchPhase.Moved) { float dot = Vector2.Dot(delta1, delta2); if (dot < 0) { Vector2 grad1 = (pos1 - initPos1).normalized; Vector2 grad2 = (pos2 - initPos2).normalized; float dot1 = Vector2.Dot(grad1, initGradient); float dot2 = Vector2.Dot(grad2, initGradient); //rotate if (dot1 < 0.7f && dot2 < 0.7f) { float curX = pos1.x - pos2.x; float curY = pos1.y - pos2.y; float curAngle = Gesture.VectorToAngle(new Vector2(curX, curY)); float val = Mathf.DeltaAngle(curAngle, prevAngle); if (Mathf.Abs(val) > 0) { AddRotVal(val); } float valueAvg = GetAverageValue(); Gesture.Rotate(valueAvg); prevAngle = curAngle; } //pinch else { Vector2 curDist = pos1 - pos2; Vector2 prevDist = (pos1 - delta1) - (pos2 - delta2); float pinch = prevDist.magnitude - curDist.magnitude; Gesture.Pinch(pinch); } } //drag if (dot > 2) { dragging = true; Vector2 posAvg = (pos1 + pos2) / 2; Vector2 dir = (delta1 + delta2) / 2; DragInfo dragInfo = new DragInfo(-1, posAvg, dir); Gesture.DualFingerDragging(dragInfo); } } lastTouchPos1 = pos1; lastTouchPos2 = pos2; } else if (Input.touchCount == 0) { //~ if(!firstTouch){ //~ firstTouch=true; //~ } if (!firstTouch) { firstTouch = true; //for tap if (Time.time - tapStartTime < shortTapTime) { if (Time.time - lastShortTapTime < doubleTapTime) { if (dTapState == _DTapState.Clear) { dTapState = _DTapState.Tap1; } else if (dTapState == _DTapState.Tap1) { if (Vector2.Distance(lastTouchPos1, lastShortTapPos) < maxDTapPosSpacing) { dTapState = _DTapState.Clear; Gesture.DFDoubleTap((startPos + lastShortTapPos) / 2); } } } else { dTapState = _DTapState.Tap1; } lastShortTapTime = Time.time; lastShortTapPos = (lastTouchPos1 + lastTouchPos2) / 2; Gesture.DFShortTap(startPos); } if (dragging) { dragging = false; Gesture.DualFingerDraggingEnd((lastTouchPos1 + lastTouchPos2) / 2); } if (charged) { charged = false; float chargeValue = Mathf.Min(1, (Time.time - tapStartTime) / maxChargeTime); ChargedInfo cInfo = new ChargedInfo((lastTouchPos1 + lastTouchPos2) / 2, chargeValue); Gesture.DFChargeEnd(cInfo); } } } }
private void SetTargetRotation() { Vector2 moveInput = new Vector2(playerInput.UpValue, playerInput.RightValue); Vector3 locolMovementDirection = new Vector3(moveInput.y, 0, moveInput.x).normalized; Vector3 forward = Quaternion.Euler(0f, cameraSetting.CurrentCamera.m_XAxis.Value, 0f) * Vector3.forward; forward.y = 0f; forward.Normalize(); Quaternion targetQuaternion; if (Mathf.Approximately(Vector3.Dot(locolMovementDirection, Vector3.forward), -1f)) { targetQuaternion = Quaternion.LookRotation(-forward); } else { Quaternion cameraToInputOffset = Quaternion.FromToRotation(Vector3.forward, locolMovementDirection); targetQuaternion = Quaternion.LookRotation(cameraToInputOffset * forward); } Vector3 resultingForword = targetQuaternion * Vector3.forward; if (IsInAttack) { Vector3 center = transform.position + transform.forward * 2.0f + transform.up; Vector3 halfExtends = new Vector3(3.0f, 1.0f, 2.0f); int count = Physics.OverlapBoxNonAlloc(center, halfExtends, overlapResultCache, targetQuaternion, weapon.targetLayers); float closestDot = 0f; Vector3 closestForward = Vector3.zero; int closesetIndex = -1; for (int i = 0; i < count; i++) { Vector3 playerToEnemy = overlapResultCache[i].transform.position - this.transform.position; playerToEnemy.y = 0; float d = Vector3.Dot(resultingForword, playerToEnemy.normalized); if (d > minEnemyDotCutOff && d > closestDot) { closestForward = playerToEnemy; closestDot = d; closesetIndex = i; } } if (closesetIndex != -1) { resultingForword = closestForward; transform.rotation = Quaternion.LookRotation(resultingForword); } } float angleCurrent = Mathf.Atan2(this.transform.forward.x, this.transform.forward.z) * Mathf.Deg2Rad; float targetAngle = Mathf.Atan2(resultingForword.x, resultingForword.z) * Mathf.Deg2Rad; angleDiff = Mathf.DeltaAngle(angleCurrent, targetAngle); targetRotation = targetQuaternion; }
public static Vector3 AngleDelta(this Vector3 self, Vector3 other) { return(new Vector3(Mathf.DeltaAngle(self.x, other.x), Mathf.DeltaAngle(self.y, other.y), Mathf.DeltaAngle(self.z, other.z))); }
/// <summary> /// Returns true if a given angle is pointing backwards from the cover. /// </summary> /// <param name="angle">Degrees in world space.</param> /// <param name="margin">Reduction in each side of the back arc of the cover.</param> public bool IsBack(float angle, float margin = 0) { float delta = Mathf.DeltaAngle(angle, Angle); return(delta <= (-90 - margin) || delta >= (90 + margin)); }