protected override bool CanDecreaseVelocity(float minSpeed) => Mathf.Abs(physicalProperties.targetVelocity.x) > minSpeed + COMPARE_VELOCITY_TOLERANCE;
private float _tmpAngularVelocity; //random angular velocity from -angularVelocity to +angularVelocity, if randomRotation is true; override public void Explode() { if (on) { _particleEmitter.useWorldSpace = useWorldSpace; _scaledDuration = timeScale * duration; _scaledDurationVariation = timeScale * durationVariation; _scaledStartRadius = size * startRadius; _particleRenderer.particleRenderMode = renderMode; if (!_delayedExplosionStarted) { _explodeDelay = explodeDelayMin + (Random.value * (explodeDelayMax - explodeDelayMin)); } if (_explodeDelay <= 0) { Color[] modifiedColors = _particleAnimator.colorAnimation; if (useExplicitColorAnimation) { modifiedColors[0] = colorAnimation[0]; modifiedColors[1] = colorAnimation[1]; modifiedColors[2] = colorAnimation[2]; modifiedColors[3] = colorAnimation[3]; modifiedColors[4] = colorAnimation[4]; } else //auto fade { modifiedColors[0] = new Color(color.r, color.g, color.b, (color.a * .7f)); modifiedColors[1] = new Color(color.r, color.g, color.b, (color.a * 1f)); modifiedColors[2] = new Color(color.r, color.g, color.b, (color.a * .5f)); modifiedColors[3] = new Color(color.r, color.g, color.b, (color.a * .3f)); modifiedColors[4] = new Color(color.r, color.g, color.b, (color.a * 0f)); } _particleAnimator.colorAnimation = modifiedColors; _particleRenderer.material = material; _particleAnimator.force = force; _tmpCount = count * detail; if (_tmpCount < 1) { _tmpCount = 1; } if (_particleEmitter.useWorldSpace == true) { _thisPos = this.gameObject.transform.position; } else { _thisPos = new Vector3(0, 0, 0); } for (int i = 1; i <= _tmpCount; i++) { _tmpPos = Vector3.Scale(Random.insideUnitSphere, new Vector3(_scaledStartRadius, _scaledStartRadius, _scaledStartRadius)); _tmpPos = _thisPos + _tmpPos; _tmpDir = Vector3.Scale(Random.insideUnitSphere, new Vector3(velocity.x, velocity.y, velocity.z)); _tmpDir.y = (_tmpDir.y + (2 * (Mathf.Abs(_tmpDir.y) * upwardsBias))); if (randomRotation == true) { _randomizedRotation = Random.Range(-1f, 1f); _tmpAngularVelocity = Random.Range(-1f, 1f) * angularVelocity; } else { _randomizedRotation = 0f; _tmpAngularVelocity = angularVelocity; } _tmpDir = Vector3.Scale(_tmpDir, new Vector3(size, size, size)); _tmpParticleSize = size * (particleSize + (Random.value * sizeVariation)); _tmpDuration = _scaledDuration + (Random.value * _scaledDurationVariation); _particleEmitter.Emit(_tmpPos, _tmpDir, _tmpParticleSize, _tmpDuration, color, _randomizedRotation, _tmpAngularVelocity); } _emitTime = Time.time; _delayedExplosionStarted = false; _explodeDelay = 0f; } else { //tell update to start reducing the start delay and call explode again when it's zero _delayedExplosionStarted = true; } } }
public void OnDrag(PointerEventData eventData) { if (!_isDragging) { return; } if (!isValid) { CancelDrag(); return; } //Set dragging object on cursor var canvas = _draggingObject.GetComponentInParent <Canvas>(); Vector3 worldPoint; RectTransformUtility.ScreenPointToWorldPointInRectangle(canvas.GetComponent <RectTransform>(), eventData.position, canvas.worldCamera, out worldPoint); switch (constraint) { case Constraint.Horizontal: worldPoint.x = _fakeElement.position.x; break; case Constraint.Vertical: worldPoint.y = _fakeElement.position.y; break; default: break; } _draggingObject.position = worldPoint; //Check everything under the cursor to find a ReorderableList EventSystem.current.RaycastAll(eventData, _raycastResults); for (int i = 0; i < _raycastResults.Count; i++) { _currentReorderableListRaycasted = _raycastResults[i].gameObject.GetComponent <ReorderableList>(); if (_currentReorderableListRaycasted != null) { break; } } //If nothing found or the list is not dropable, put the fake element outsite if (_currentReorderableListRaycasted == null || _currentReorderableListRaycasted.IsDropable == false) { RefreshSizes(); _fakeElement.transform.SetParent(_reorderableList.DraggableArea, false); } //Else find the best position on the list and put fake element on the right index else { if (!IsTransferable && _reorderableList != _currentReorderableListRaycasted) { return; } if (_fakeElement.parent != _currentReorderableListRaycasted) { _fakeElement.SetParent(_currentReorderableListRaycasted.Content, false); } float minDistance = float.PositiveInfinity; int targetIndex = 0; float dist = 0; for (int j = 0; j < _currentReorderableListRaycasted.Content.childCount; j++) { var c = _currentReorderableListRaycasted.Content.GetChild(j).GetComponent <RectTransform>(); if (_currentReorderableListRaycasted.ContentLayout is VerticalLayoutGroup) { dist = Mathf.Abs(c.position.y - worldPoint.y); } else if (_currentReorderableListRaycasted.ContentLayout is HorizontalLayoutGroup) { dist = Mathf.Abs(c.position.x - worldPoint.x); } else if (_currentReorderableListRaycasted.ContentLayout is GridLayoutGroup) { dist = (Mathf.Abs(c.position.x - worldPoint.x) + Mathf.Abs(c.position.y - worldPoint.y)); } if (dist < minDistance) { minDistance = dist; targetIndex = j; } } RefreshSizes(); _fakeElement.SetSiblingIndex(targetIndex); _fakeElement.gameObject.SetActive(true); } }
public void UpdateAnimation() { if (aniInfo == null || IsPause()) { return; } if (isInTransition) { transitionTimer += Time.deltaTime; float weight = transitionTimer / transitionDuration; transitionProgress = Mathf.Min(weight, 1.0f); if (transitionProgress >= 1.0f) { isInTransition = false; preAniIndex = -1; preAniFrame = -1; } } float speed = playSpeed * speedParameter; curFrame += speed * Time.deltaTime * aniInfo[aniIndex].fps; int totalFrame = aniInfo[aniIndex].totalFrame; switch (wrapMode) { case WrapMode.Loop: { if (curFrame < 0f) { curFrame += (totalFrame - 1); } else if (curFrame > totalFrame - 1) { curFrame -= (totalFrame - 1); } break; } case WrapMode.PingPong: { if (curFrame < 0f) { speedParameter = Mathf.Abs(speedParameter); curFrame = Mathf.Abs(curFrame); } else if (curFrame > totalFrame - 1) { speedParameter = -Mathf.Abs(speedParameter); curFrame = 2 * (totalFrame - 1) - curFrame; } break; } case WrapMode.Default: case WrapMode.Once: { if (curFrame < 0f || curFrame > totalFrame - 1.0f) { Pause(); } break; } } curFrame = Mathf.Clamp(curFrame, 0f, totalFrame - 1); for (int i = 0; i != listAttachment.Count; ++i) { AnimationInstancing attachment = listAttachment[i]; attachment.transform.position = transform.position; attachment.transform.rotation = transform.rotation; } UpdateAnimationEvent(); }
public bool BoxVsSphereCollision(CustomBoxCollider box, CustomSphereCollider sphere, out CustomCollisionInfo info) { info = new CustomCollisionInfo(); var spherePosition = sphere.transform.position + sphere.colliderOffset; var boxPosition = box.transform.position + box.colliderOffset; //List<Vector3> box1Points = box.GetOrientedBoxBounds().GetPoints(); //List<Vector3> box2Points = new List<Vector3>(); //box2Points.Add(spherePosition + sphere.U() * sphere.radius); //box2Points.Add(spherePosition - sphere.U() * sphere.radius); //box2Points.Add(spherePosition + sphere.V() * sphere.radius); //box2Points.Add(spherePosition - sphere.V() * sphere.radius); //box2Points.Add(spherePosition + sphere.W() * sphere.radius); //box2Points.Add(spherePosition - sphere.W() * sphere.radius); //var P1 = GetMinMaxObj(box1Points, box.V()); //var P2 = GetMinMaxObj(box2Points, box.V()); //var Q1 = GetMinMaxObj(box1Points, box.U()); //var Q2 = GetMinMaxObj(box2Points, box.U()); //var R1 = GetMinMaxObj(box1Points, box.W()); //var R2 = GetMinMaxObj(box2Points, box.W()); //var S1 = GetMinMaxObj(box1Points, sphere.V()); //var S2 = GetMinMaxObj(box2Points, sphere.V()); //var T1 = GetMinMaxObj(box1Points, sphere.U()); //var T2 = GetMinMaxObj(box2Points, sphere.U()); //var U1 = GetMinMaxObj(box1Points, sphere.W()); //var U2 = GetMinMaxObj(box2Points, sphere.W()); //bool P = P1.max < P2.min || P2.max < P1.min; //bool Q = Q1.max < Q2.min || Q2.max < Q1.min; //bool R = R1.max < R2.min || R2.max < R1.min; //bool S = S1.max < S2.min || S2.max < S1.min; //bool T = T1.max < T2.min || T2.max < T1.min; //bool U = U1.max < U2.min || U2.max < U1.min; ////Check if seperated //bool res = P || Q || R || S || T || U; //if (!res) //{ // info.intersectionSize.x = // Mathf.Max(Mathf.Min((spherePosition + (sphere.U() * sphere.radius + sphere.V() * sphere.radius + sphere.W() * sphere.radius)).x, box.GetOrientedBoxBounds().max.x), 0); // info.intersectionSize.y = // Mathf.Max(Mathf.Min((spherePosition + (sphere.U() * sphere.radius + sphere.V() * sphere.radius + sphere.W() * sphere.radius)).y, box.GetOrientedBoxBounds().max.y), 0); // info.intersectionSize.z = // Mathf.Max(Mathf.Min((spherePosition + (sphere.U() * sphere.radius + sphere.V() * sphere.radius + sphere.W() * sphere.radius)).z, box.GetOrientedBoxBounds().max.z), 0); // DrawBoundingVolume(box, Color.red, true); // DrawBoundingVolume(sphere, Color.red, true, CustomCollider.ColliderType.Sphere); //} //return res; var normal = (boxPosition - spherePosition).normalized; var rad = Mathf.Abs(Vector3.Dot(box.U(), normal) + Vector3.Dot(box.V(), normal) + Vector3.Dot(box.W(), normal)); var dot = Vector3.Dot(boxPosition, normal) - Vector3.Dot(spherePosition, normal); if (dot < rad) { var xMax1 = box.GetOrientedBoxBounds().max.x; var yMax1 = box.GetOrientedBoxBounds().max.y; var zMax1 = box.GetOrientedBoxBounds().max.z; var xMax2 = spherePosition.x + sphere.radius; var yMax2 = spherePosition.y + sphere.radius; var zMax2 = spherePosition.z + sphere.radius; info.intersectionSize.x = Mathf.Max(Mathf.Min(xMax2, xMax1), 0); info.intersectionSize.y = Mathf.Max(Mathf.Min(yMax2, yMax1), 0); info.intersectionSize.z = Mathf.Max(Mathf.Min(zMax2, zMax1), 0); DrawBoundingVolume(box, Color.red, true); DrawBoundingVolume(sphere, Color.red, true, CustomCollider.ColliderType.Sphere); return(true); } return(false); //Vector3 v; //var centerBox = box.transform.position + box.colliderOffset; //var currentCorner = box.GetOrientedBoxBounds().GetPoints()[0]; //var max = Vector3.Distance(centerBox, spherePosition); //var box2sphere = boxPosition - spherePosition; //var box2SphereNormalised = box2sphere.normalized; //var points = box.GetOrientedBoxBounds().GetPoints(); //var closestPoint = centerBox; //for (int i = 1; i < points.Count; ++i) //{ // currentCorner = points[i]; // if (Vector3.Distance(currentCorner, spherePosition) < max) // closestPoint = currentCorner; //} //if ((sphere.radius - (spherePosition - closestPoint).magnitude) <= 0) // return false; //else //{ // var xMax1 = box.GetOrientedBoxBounds().max.x; // var yMax1 = box.GetOrientedBoxBounds().max.y; // var zMax1 = box.GetOrientedBoxBounds().max.z; // var xMax2 = sphere.radius - (spherePosition.x - closestPoint.x); // var yMax2 = sphere.radius - (spherePosition.y - closestPoint.y); // var zMax2 = sphere.radius - (spherePosition.z - closestPoint.z); // // info.intersectionSize.x = sphere.radius - (spherePosition.x - closestPoint.x); // // info.intersectionSize.y = sphere.radius - (spherePosition.y - closestPoint.y); // // info.intersectionSize.z = sphere.radius - (spherePosition.z - closestPoint.z); // info.intersectionSize.x = Mathf.Max(Mathf.Min(xMax2, xMax1), 0) * 2; // info.intersectionSize.y = Mathf.Max(Mathf.Min(yMax2, yMax1), 0) * 2; // info.intersectionSize.z = Mathf.Max(Mathf.Min(zMax2, zMax1), 0) * 2; // return true; //} //if (box2sphere.magnitude - max - sphere.radius > 0 && box2sphere.magnitude > 0) // return false; //DrawBoundingVolume(box, Color.red, true); //DrawBoundingVolume(sphere, Color.red, true, CustomCollider.ColliderType.Sphere); //var xMin1 = box.GetOrientedBoxBounds().min.x; //var xMax1 = box.GetOrientedBoxBounds().max.x; //var yMin1 = box.GetOrientedBoxBounds().min.y; //var yMax1 = box.GetOrientedBoxBounds().max.y; //var zMin1 = box.GetOrientedBoxBounds().min.z; //var zMax1 = box.GetOrientedBoxBounds().max.z; //var xMin2 = spherePosition.x - sphere.radius; //var xMax2 = spherePosition.x + sphere.radius; //var yMin2 = spherePosition.y - sphere.radius; //var yMax2 = spherePosition.y + sphere.radius; //var zMin2 = spherePosition.z - sphere.radius; //var zMax2 = spherePosition.z + sphere.radius; //info.intersectionSize.x = Mathf.Max(Mathf.Min(xMax2, xMax1), 0); //info.intersectionSize.y = Mathf.Max(Mathf.Min(yMax2, yMax1), 0); //info.intersectionSize.z = Mathf.Max(Mathf.Min(zMax2, zMax1), 0); //return true; }
public void Update(OVRPose headPose, OVRPose remotePose, UnityEngine.XR.XRNode handNode, bool recenteredController, out OVRPose outPose) { float eyeYaw; float eyePitch; float eyeRoll; GetYawPitchRoll(headPose.orientation, out eyeYaw, out eyePitch, out eyeRoll); TorsoYaw = ConstrainTorsoYaw(headPose.orientation, TorsoYaw); if (recenteredController) { TorsoYaw = eyeYaw; } OVRPose FootPose = MakePose(Quaternion.AngleAxis(TorsoYaw * Mathf.Rad2Deg, new Vector3(0.0f, 1.0f, 0.0f)), new Vector3(headPose.position.x, headPose.position.y, headPose.position.z)); float handSign = (handNode == UnityEngine.XR.XRNode.LeftHand) ? -1.0f : 1.0f; OVRPose pose = Skeleton[ClavicleJointIdx].Key; pose.position.x = Mathf.Abs(Skeleton[ClavicleJointIdx].Key.position.x) * handSign; Skeleton[ClavicleJointIdx] = new OvrJoint(pose, Skeleton[ClavicleJointIdx].Value); List <OvrJointMod> jointMods = new List <OvrJointMod>(); Quaternion remoteRot = new Quaternion(remotePose.orientation.x, remotePose.orientation.y, remotePose.orientation.z, remotePose.orientation.w); float MAX_ROLL = Mathf.PI * 0.5f; float remoteYaw = 0.0f; float remotePitch = 0.0f; float remoteRoll = 0.0f; GetYawPitchRoll(remoteRot, out remoteYaw, out remotePitch, out remoteRoll); if (remoteRoll >= -MAX_ROLL && remoteRoll <= MAX_ROLL) { LastUnclampedRoll = remoteRoll; } else { remoteRoll = LastUnclampedRoll; } remoteRot = Quaternion.AngleAxis(remoteYaw * Mathf.Rad2Deg, new Vector3(0, 1, 0)) * Quaternion.AngleAxis(remotePitch * Mathf.Rad2Deg, new Vector3(1, 0, 0)) * Quaternion.AngleAxis(remoteRoll * Mathf.Rad2Deg, new Vector3(0, 0, 1)); Quaternion localRemoteRot = Quaternion.Inverse(FootPose.orientation) * (remoteRot); Quaternion shoulderRot = Quaternion.Slerp(Quaternion.identity, localRemoteRot, 0.0f); Quaternion elbowRot = Quaternion.Slerp(Quaternion.identity, localRemoteRot, 0.6f); Quaternion wristRot = Quaternion.Slerp(Quaternion.identity, localRemoteRot, 0.4f); jointMods.Add(new OvrJointMod(ShoulderJointIdx, MakePose(shoulderRot, new Vector3(0.0f, 0.0f, 0.0f)))); jointMods.Add(new OvrJointMod(ElbowJointIdx, MakePose(elbowRot, new Vector3(0.0f, 0.0f, 0.0f)))); jointMods.Add(new OvrJointMod(WristJointIdx, MakePose(wristRot, new Vector3(0.0f, 0.0f, 0.0f)))); Transform(FootPose, Skeleton, jointMods, ref TransformedJoints); outPose = MakePose(new Quaternion(remotePose.orientation.x, remotePose.orientation.y, remotePose.orientation.z, remotePose.orientation.w), TransformedJoints[TransformedJoints.Count - 1].Key.position); }
/// <summary>Async method for moving the graph</summary> private IEnumerator UpdateGraphCoroutine() { // Find the direction that we want to move the graph in. // Calcuculate this in graph space (where a distance of one is the size of one node) Vector3 dir = PointToGraphSpace(target.position) - PointToGraphSpace(graph.center); // Snap to a whole number of nodes dir.x = Mathf.Round(dir.x); dir.z = Mathf.Round(dir.z); dir.y = 0; // Nothing do to if (dir == Vector3.zero) { yield break; } // Number of nodes to offset in each direction Int2 offset = new Int2(-Mathf.RoundToInt(dir.x), -Mathf.RoundToInt(dir.z)); // Move the center (this is in world units, so we need to convert it back from graph space) graph.center += graph.transform.TransformVector(dir); graph.UpdateTransform(); // Cache some variables for easier access int width = graph.width; int depth = graph.depth; GridNodeBase[] nodes; // Layers are required when handling LayeredGridGraphs int layers = graph.LayerCount; nodes = graph.nodes; // Create a temporary buffer required for the calculations if (buffer == null || buffer.Length != width * depth) { buffer = new GridNodeBase[width * depth]; } // Check if we have moved less than a whole graph width all directions // If we have moved more than this we can just as well recalculate the whole graph if (Mathf.Abs(offset.x) <= width && Mathf.Abs(offset.y) <= depth) { IntRect recalculateRect = new IntRect(0, 0, offset.x, offset.y); // If offset.x < 0, adjust the rect if (recalculateRect.xmin > recalculateRect.xmax) { int tmp2 = recalculateRect.xmax; recalculateRect.xmax = width + recalculateRect.xmin; recalculateRect.xmin = width + tmp2; } // If offset.y < 0, adjust the rect if (recalculateRect.ymin > recalculateRect.ymax) { int tmp2 = recalculateRect.ymax; recalculateRect.ymax = depth + recalculateRect.ymin; recalculateRect.ymin = depth + tmp2; } // Connections need to be recalculated for the neighbours as well, so we need to expand the rect by 1 var connectionRect = recalculateRect.Expand(1); // Makes sure the rect stays inside the grid connectionRect = IntRect.Intersection(connectionRect, new IntRect(0, 0, width, depth)); // Offset each node by the #offset variable // nodes which would end up outside the graph // will wrap around to the other side of it for (int l = 0; l < layers; l++) { int layerOffset = l * width * depth; for (int z = 0; z < depth; z++) { int pz = z * width; int tz = ((z + offset.y + depth) % depth) * width; for (int x = 0; x < width; x++) { buffer[tz + ((x + offset.x + width) % width)] = nodes[layerOffset + pz + x]; } } yield return(null); // Copy the nodes back to the graph // and set the correct indices for (int z = 0; z < depth; z++) { int pz = z * width; for (int x = 0; x < width; x++) { int newIndex = pz + x; var node = buffer[newIndex]; if (node != null) { node.NodeInGridIndex = newIndex; } nodes[layerOffset + newIndex] = node; } // Calculate the limits for the region that has been wrapped // to the other side of the graph int xmin, xmax; if (z >= recalculateRect.ymin && z < recalculateRect.ymax) { xmin = 0; xmax = depth; } else { xmin = recalculateRect.xmin; xmax = recalculateRect.xmax; } for (int x = xmin; x < xmax; x++) { var node = buffer[pz + x]; if (node != null) { // Clear connections on all nodes that are wrapped and placed on the other side of the graph. // This is both to clear any custom connections (which do not really make sense after moving the node) // and to prevent possible exceptions when the node will later (possibly) be destroyed because it was // not needed anymore (only for layered grid graphs). node.ClearConnections(false); } } } yield return(null); } // The calculation will only update approximately this number of // nodes per frame. This is used to keep CPU load per frame low int yieldEvery = 1000; // To avoid the update taking too long, make yieldEvery somewhat proportional to the number of nodes that we are going to update int approxNumNodesToUpdate = Mathf.Max(Mathf.Abs(offset.x), Mathf.Abs(offset.y)) * Mathf.Max(width, depth); yieldEvery = Mathf.Max(yieldEvery, approxNumNodesToUpdate / 10); int counter = 0; // Recalculate the nodes // Take a look at the image in the docs for the UpdateGraph method // to see which nodes are being recalculated. for (int z = 0; z < depth; z++) { int xmin, xmax; if (z >= recalculateRect.ymin && z < recalculateRect.ymax) { xmin = 0; xmax = width; } else { xmin = recalculateRect.xmin; xmax = recalculateRect.xmax; } for (int x = xmin; x < xmax; x++) { graph.RecalculateCell(x, z, false, false); } counter += (xmax - xmin); if (counter > yieldEvery) { counter = 0; yield return(null); } } for (int z = 0; z < depth; z++) { int xmin, xmax; if (z >= connectionRect.ymin && z < connectionRect.ymax) { xmin = 0; xmax = width; } else { xmin = connectionRect.xmin; xmax = connectionRect.xmax; } for (int x = xmin; x < xmax; x++) { graph.CalculateConnections(x, z); } counter += (xmax - xmin); if (counter > yieldEvery) { counter = 0; yield return(null); } } yield return(null); // Calculate all connections for the nodes along the boundary // of the graph, these always need to be updated /// <summary>TODO: Optimize to not traverse all nodes in the graph, only those at the edges</summary> for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++) { if (x == 0 || z == 0 || x == width - 1 || z == depth - 1) { graph.CalculateConnections(x, z); } } } } else { // The calculation will only update approximately this number of // nodes per frame. This is used to keep CPU load per frame low int yieldEvery = Mathf.Max(depth * width / 20, 1000); int counter = 0; // Just update all nodes for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++) { graph.RecalculateCell(x, z); } counter += width; if (counter > yieldEvery) { counter = 0; yield return(null); } } // Recalculate the connections of all nodes for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++) { graph.CalculateConnections(x, z); } counter += width; if (counter > yieldEvery) { counter = 0; yield return(null); } } } }
/// <summary> /// This should be called by our HitboxManager /// </summary> public override void UpdateBoundsOfCollider() { BoundsRect b = new BoundsRect(); Vector2 localScale; if (!ignoreParentScale) { localScale = this.transform.localScale; localScale = new Vector2(Mathf.Abs(localScale.x), Mathf.Abs(localScale.y)); } else { localScale = Vector2.one; } Vector2 scaledBoxColliderSize = new Vector2(boxColliderSize.x * localScale.x, boxColliderSize.y * localScale.y); Vector2 origin = this.transform.position + (isStatic ? Vector3.zero : Vector3.up * scaledBoxColliderSize.y / 2) + new Vector3(colliderOffset.x * localScale.x, colliderOffset.y * localScale.y); b.center = origin; b.topLeft = origin + (Vector2.up * scaledBoxColliderSize.y / 2) - (Vector2.right * scaledBoxColliderSize.x / 2); b.topRight = origin + (Vector2.up * scaledBoxColliderSize.y / 2) + (Vector2.right * scaledBoxColliderSize.x / 2); b.bottomLeft = origin - (Vector2.up * scaledBoxColliderSize.y / 2) - (Vector2.right * scaledBoxColliderSize.x / 2); b.bottomRight = origin - (Vector2.up * scaledBoxColliderSize.y / 2) + (Vector2.right * scaledBoxColliderSize.x / 2); this.bounds = b; if (!isStatic) { verticalCheckBounds = this.bounds; horizontalCheckBounds = this.bounds; float verticalOffset = 0; float horizontalOffset = 0; verticalCheckBounds.topLeft.x += HorizontalBuffer / 2; verticalCheckBounds.bottomLeft.x += HorizontalBuffer / 2; verticalCheckBounds.topRight.x -= HorizontalBuffer / 2; verticalCheckBounds.bottomRight.x -= HorizontalBuffer / 2; horizontalCheckBounds.topLeft.y -= VerticalBuffer / 2; horizontalCheckBounds.topRight.y -= VerticalBuffer / 2; horizontalCheckBounds.bottomLeft.y += VerticalBuffer / 2; horizontalCheckBounds.bottomRight.y += VerticalBuffer / 2; if (Mathf.Abs(rigid.Velocity.y) > 0) { verticalOffset = Mathf.Sign(rigid.Velocity.y) * Mathf.Max(VerticalBuffer, Mathf.Abs(rigid.Velocity.y * Overseer.DELTA_TIME)); } if (Mathf.Abs(rigid.Velocity.x) > 0) { horizontalOffset = Mathf.Sign(rigid.Velocity.x) * Mathf.Max(HorizontalBuffer, Mathf.Abs(rigid.Velocity.x * Overseer.DELTA_TIME)); } verticalCheckBounds.SetOffset(Vector2.up * verticalOffset); horizontalCheckBounds.SetOffset(Vector2.right * horizontalOffset); } }
void Animations() { anim.SetBool("ground", isGrounded); anim.SetFloat("speed", Mathf.Abs(Input.GetAxisRaw("Horizontal"))); anim.SetFloat("vSpeed", rb.velocity.y); }
public void Move(Connection conn, HazelReader reader) { Player p = playerByConnection [conn]; int3 targetPosition = reader.ReadInt3(); bool pending = reader.ReadBool; if (!p.doneTurn && targetPosition.y <= p.position.y) { //and it is within 1 block range from him, int3 absDeltaPos = targetPosition - p.position; absDeltaPos = new int3(Mathf.Abs(absDeltaPos.x), Mathf.Abs(absDeltaPos.y), Mathf.Abs(absDeltaPos.z)); if ((absDeltaPos.y == 0 && absDeltaPos.x == 2) || (absDeltaPos.x == 1 && absDeltaPos.y == 1)) { //and target platform available Platform dest = platforms.SingleOrDefault(w => w.position == targetPosition); if (dest != null) { //and there are no player nor wall on the targetPosition, if (!players.Exists(p2 => p2.position.xz == targetPosition.xz && targetPosition.y == p.position.y)) { //turn done playerById[id].doneTurn = true; turnRemaining--; //move if (pending) { pendingMove.Add(id, dest); } else { UpdateTransform(p, dest); } } } } } }
public void Jump(int id, int3 targetPosition) { //if he's it and hasnt done his turn Player p = playerById[id]; if (it == id && !p.doneTurn) { bool validJump = false; int3 deltaPos = targetPosition - p.position; int3 absDeltaPos = new int3(Mathf.Abs(deltaPos.x), Mathf.Abs(deltaPos.y), Mathf.Abs(deltaPos.z)); //and destination platform available Platform dest = platforms.SingleOrDefault(w => w.position == targetPosition); if (dest != null) { //and it is within 1 block range from him if ((absDeltaPos.y == 0 && absDeltaPos.x == 2) || (absDeltaPos.x == 1 && absDeltaPos.y == 1)) { if (targetPosition.y - p.position.y < 1) { validJump = true; } //or it is within 2 blocks range straight from him } else if ((absDeltaPos.y == 2 && (absDeltaPos.x == 0 || absDeltaPos.x == 2)) || (absDeltaPos.y == 0 && absDeltaPos.x == 4)) { //and there are no wall blocking the path to targetPosition int2 pos = (playerById [id].position.xz + new int2(deltaPos.x / 2, deltaPos.z / 2)); if (!platforms.Exists(w => w.position.xz == pos && w.position.y - p.position.y == 2)) { validJump = true; } //or it is within 2 blocks range not straight from him } else if (absDeltaPos.x == 3 && absDeltaPos.y == 1) { //and there are no wall blocking the path to targetPosition int2 pos1 = playerById[id].position.xz + new int2(deltaPos.x / 3, deltaPos.z); int2 pos2 = playerById [id].position.xz + new int2(2 * deltaPos.x / 3, 0); if (!platforms.Exists(w => (w.position.xz == pos1 || w.position.xz == pos2) && w.position.y - p.position.y == 2)) { validJump = true; } } } if (validJump) { //turn done p.doneTurn = true; turnRemaining--; //jump pendingMove.Add(id, dest); } } }
private void PlayAnimations(Vector2 mvmtDelta) { if (!hasAnimator) { return; } if (!IsGrounded()) { // JUMP/FALL ANIMS if (rigidbody.velocity.y < 0.1f) // Falling { meshAnimator.StartAnimFromName(lastFacedRight ? "_playerFallRight" : "_playerFallLeft"); return; } else if (rigidbody.velocity.y > 0.1f) // Jumping { meshAnimator.StartAnimFromName(lastFacedRight ? "_playerJumpRight" : "_playerJumpLeft"); return; } } // RUN/WALK ANIMS if (Mathf.Abs(mvmtDelta.x) > 0.5f) { if (mvmtDelta.x > 0.5f) //Running Right { meshAnimator.StartAnimFromName("_playerRunRight"); lastFacedRight = true; } else //Running Left { meshAnimator.StartAnimFromName("_playerRunLeft"); lastFacedRight = false; } return; } else if (Mathf.Abs(mvmtDelta.x) > 0.08f) { if (mvmtDelta.x > 0.08f) //Walking Right { meshAnimator.StartAnimFromName("_playerWalkRight"); lastFacedRight = true; } else //Walking Left { meshAnimator.StartAnimFromName("_playerWalkLeft"); lastFacedRight = false; } return; } if (lastFacedRight) { meshAnimator.StartAnimFromName("_playerIdleRight"); } else { meshAnimator.StartAnimFromName("_playerIdleLeft"); } }
private void DrawTweenedHand(Vector3 position, Mesh handsMesh, Material material, Quaternion quat, TweenThing tweenThing, bool portrait, bool noTween) { if (position == Vector3.zero || handsMesh == null || material == null) { return; } if (this.ShouldBeIgnored()) { return; } if (!HarmonyPatchesFS.AnimatorIsOpen() && Find.TickManager.TicksGame == this.CompAnimator.LastPosUpdate[(int) tweenThing] || HarmonyPatchesFS.AnimatorIsOpen() && MainTabWindow_BaseAnimator.Pawn != this.Pawn) { position = this.CompAnimator.LastPosition[(int) tweenThing]; } else { Pawn_PathFollower pawnPathFollower = this.Pawn.pather; if (pawnPathFollower != null && pawnPathFollower.MovedRecently(5)) { noTween = true; } this.CompAnimator.LastPosUpdate[(int) tweenThing] = Find.TickManager.TicksGame; Vector3Tween tween = this.CompAnimator.Vector3Tweens[(int) tweenThing]; switch (tween.State) { case TweenState.Running: if (noTween || this.CompAnimator.IsMoving) { tween.Stop(StopBehavior.ForceComplete); } position = tween.CurrentValue; break; case TweenState.Paused: break; case TweenState.Stopped: if (noTween || (this.CompAnimator.IsMoving)) { break; } ScaleFunc scaleFunc = ScaleFuncs.SineEaseOut; Vector3 start = this.CompAnimator.LastPosition[(int) tweenThing]; float distance = Vector3.Distance(start, position); float duration = Mathf.Abs(distance * 50f); if (start != Vector3.zero && duration > 12f) { start.y = position.y; tween.Start(start, position, duration, scaleFunc); position = start; } break; } this.CompAnimator.LastPosition[(int) tweenThing] = position; } // tweener.PreThingPosCalculation(tweenThing, noTween); GenDraw.DrawMeshNowOrLater( handsMesh, position, quat, material, portrait); }
public void IsClickCheck() { if (TrueOrFalse == false) { return; } if (!bIsOnline) { GameObject obj = UICamera.hoveredObject; BlackNameOrRedName(obj);//是否点击到棋子 如果是 就得到棋子 if (obj.name.Substring(0, 1) != "i") { obj = obj.gameObject.transform.parent.gameObject;//得到他的父容器 } int x = System.Convert.ToInt32((obj.transform.localPosition.x + 263) / 195); int y = System.Convert.ToInt32(Mathf.Abs((obj.transform.localPosition.y - 302) / 192)); int Result = IsBlackOrRed(x, y);//判断点击到了什么 switch (Result) { case 0: //点击到了空 是否要走棋 //如果点击到了空格 就把对象清空 for (int i = 1; i <= 90; i++) { GameObject Clear = GameObject.Find("prefabs" + i.ToString()); Destroy(Clear); } ToY = y; ToX = x; if (ChessMove) { //红色走 if (RedName == null) { return; } string sssRed = RedName; //记录红色棋子的名字 bool ba = rules.IsValidMove(Board.chess, FromX, FromY, ToX, ToY); if (!ba) { return; } int a = Board.chess[FromY, FromX]; int b = Board.chess[ToY, ToX]; chzh.AddChess(ChessChongzhi.Count, FromX, FromY, ToX, ToY, true, a, b); str = "黑方走"; IsMove(RedName, obj, FromX, FromY, ToX, ToY); //走了 KingPosition.JiangJunCheck(); ChessMove = false; //getString(); if (str == "红色棋子胜利") { return; //因为没有携程关系 每次进入黑色走棋的时候都判断 棋局是否结束 } BlackName = null; RedName = null; return; //执行走棋 } else { //黑色走 if (BlackName == null) { return; } bool ba = rules.IsValidMove(Board.chess, FromX, FromY, ToX, ToY); if (!ba) { return; } //ChessChongzhi chzh = new ChessChongzhi(); int a = Board.chess[FromY, FromX]; int b = Board.chess[ToY, ToX]; chzh.AddChess(ChessChongzhi.Count, FromX, FromY, ToX, ToY, true, a, b); str = "红方走"; IsMove(BlackName, obj, FromX, FromY, ToX, ToY); //黑色走棋 ChessMove = true; KingPosition.JiangJunCheck(); } break; case 1: //点击到了黑色 是否选中 还是 红色要吃子 if (!ChessMove) { FromX = x; FromY = y; for (int i = 1; i <= 90; i++) { GameObject Clear = GameObject.Find("prefabs" + i.ToString()); Destroy(Clear); } can.ClickChess(FromX, FromY); } else { for (int i = 1; i <= 90; i++) { GameObject Clear = GameObject.Find("prefabs" + i.ToString()); Destroy(Clear); } if (RedName == null) { return; } ToX = x; ToY = y; bool ba = rules.IsValidMove(Board.chess, FromX, FromY, ToX, ToY); if (!ba) { return; } int a = Board.chess[FromY, FromX]; int b = Board.chess[ToY, ToX]; chzh.AddChess(ChessChongzhi.Count, FromX, FromY, ToX, ToY, true, a, b); //看看是否能播放音乐 IsEat(RedName, BlackName, FromX, FromY, ToX, ToY); ChessMove = false; //红色吃子 变黑色走 str = "黑方走"; KingPosition.JiangJunCheck(); if (str == "红色棋子胜利") { return; //因为没有携程关系 每次进入黑色走棋的时候都判断 棋局是否结束 } RedName = null; BlackName = null; return; } break; case 2: //点击到了红色 是否选中 还是黑色要吃子 if (ChessMove) { FromX = x; FromY = y; for (int i = 1; i <= 90; i++) { GameObject Clear = GameObject.Find("prefabs" + i.ToString()); Destroy(Clear); } can.ClickChess(FromX, FromY); } else { for (int i = 1; i <= 90; i++) { GameObject Clear = GameObject.Find("prefabs" + i.ToString()); Destroy(Clear); } if (BlackName == null) { return; } ToX = x; ToY = y; bool ba = rules.IsValidMove(Board.chess, FromX, FromY, ToX, ToY); if (!ba) { return; } //ChessChongzhi chzh = new ChessChongzhi(); int a = Board.chess[FromY, FromX]; int b = Board.chess[ToY, ToX]; chzh.AddChess(ChessChongzhi.Count, FromX, FromY, ToX, ToY, true, a, b); //看看是否能播放音乐 IsEat(BlackName, RedName, FromX, FromY, ToX, ToY); RedName = null; BlackName = null; ChessMove = true; str = "红方走"; KingPosition.JiangJunCheck(); } break; } } else { if (!GobangClient.isConnected()) { return; } if ((GameManager.curTurn == GameManager.userColor) && TrueOrFalse) { GameObject obj = UICamera.hoveredObject; BlackNameOrRedName(obj);//是否点击到棋子 如果是 就得到棋子 if (obj.name.Substring(0, 1) != "i") { obj = obj.gameObject.transform.parent.gameObject;//得到他的父容器 } int x = System.Convert.ToInt32((obj.transform.localPosition.x + 263) / 195); int y = System.Convert.ToInt32(Mathf.Abs((obj.transform.localPosition.y - 302) / 192)); int Result = IsBlackOrRed(x, y);//判断点击到了什么 switch (Result) { case 0: //点击到了空 是否要走棋 //如果点击到了空格 就把对象清空 for (int i = 1; i <= 90; i++) { GameObject Clear = GameObject.Find("prefabs" + i.ToString()); Destroy(Clear); } ToY = y; ToX = x; if (ChessMove) { //红色走 if (RedName == null) { return; } string sssRed = RedName; //记录红色棋子的名字 bool ba = rules.IsValidMove(Board.chess, FromX, FromY, ToX, ToY); if (!ba) { return; } int a = Board.chess[FromY, FromX]; int b = Board.chess[ToY, ToX]; chzh.AddChess(ChessChongzhi.Count, FromX, FromY, ToX, ToY, true, a, b); str = "黑方走"; IsMove(RedName, obj, FromX, FromY, ToX, ToY); //走了 KingPosition.JiangJunCheck(); ChessMove = false; //getString(); if (str == "红色棋子胜利") { return; //因为没有携程关系 每次进入黑色走棋的时候都判断 棋局是否结束 } BlackName = null; RedName = null; SendMoveMessage(FromX, FromY, ToX, ToY); return; //执行走棋 } else { //黑色走 if (BlackName == null) { return; } bool ba = rules.IsValidMove(Board.chess, FromX, FromY, ToX, ToY); if (!ba) { return; } //ChessChongzhi chzh = new ChessChongzhi(); int a = Board.chess[FromY, FromX]; int b = Board.chess[ToY, ToX]; chzh.AddChess(ChessChongzhi.Count, FromX, FromY, ToX, ToY, true, a, b); str = "红方走"; IsMove(BlackName, obj, FromX, FromY, ToX, ToY); //黑色走棋 ChessMove = true; KingPosition.JiangJunCheck(); SendMoveMessage(FromX, FromY, ToX, ToY); } break; case 1: //点击到了黑色 是否选中 还是 红色要吃子 if (!ChessMove) { FromX = x; FromY = y; for (int i = 1; i <= 90; i++) { GameObject Clear = GameObject.Find("prefabs" + i.ToString()); Destroy(Clear); } can.ClickChess(FromX, FromY); } else { for (int i = 1; i <= 90; i++) { GameObject Clear = GameObject.Find("prefabs" + i.ToString()); Destroy(Clear); } if (RedName == null) { return; } ToX = x; ToY = y; bool ba = rules.IsValidMove(Board.chess, FromX, FromY, ToX, ToY); if (!ba) { return; } int a = Board.chess[FromY, FromX]; int b = Board.chess[ToY, ToX]; chzh.AddChess(ChessChongzhi.Count, FromX, FromY, ToX, ToY, true, a, b); //红色吃子 变黑色走 str = "黑方走"; IsEat(RedName, BlackName, FromX, FromY, ToX, ToY); ChessMove = false; KingPosition.JiangJunCheck(); if (str == "红色棋子胜利") { return; //因为没有携程关系 每次进入黑色走棋的时候都判断 棋局是否结束 } RedName = null; BlackName = null; SendEatMessage(FromX, FromY, ToX, ToY); return; } break; case 2: //点击到了红色 是否选中 还是黑色要吃子 if (ChessMove) { FromX = x; FromY = y; for (int i = 1; i <= 90; i++) { GameObject Clear = GameObject.Find("prefabs" + i.ToString()); Destroy(Clear); } can.ClickChess(FromX, FromY); } else { for (int i = 1; i <= 90; i++) { GameObject Clear = GameObject.Find("prefabs" + i.ToString()); Destroy(Clear); } if (BlackName == null) { return; } ToX = x; ToY = y; bool ba = rules.IsValidMove(Board.chess, FromX, FromY, ToX, ToY); if (!ba) { return; } //ChessChongzhi chzh = new ChessChongzhi(); int a = Board.chess[FromY, FromX]; int b = Board.chess[ToY, ToX]; chzh.AddChess(ChessChongzhi.Count, FromX, FromY, ToX, ToY, true, a, b); str = "红方走"; IsEat(BlackName, RedName, FromX, FromY, ToX, ToY); RedName = null; BlackName = null; ChessMove = true; KingPosition.JiangJunCheck(); SendEatMessage(FromX, FromY, ToX, ToY); } break; } } } }
/// <summary> /// Creates the two dimensional volume described by the largest rectangle that /// is contained withing the play space geometry and the configured height. /// </summary> private void CreateInscribedBounds() { // We always use the same seed so that from run to run, the inscribed bounds are consistent. rectangularBounds = new InscribedRectangle(Bounds, Mathf.Abs("Mixed Reality Toolkit".GetHashCode())); }
// Update is called once per frame void Update() { //use this to have the floor be fast on flat, and hold on the tilt (a normal sin wave) //rotation = amplitude * Mathf.Sin ((Time.realtimeSinceStartup*speed) + offset); //use this to have the floor hold on flat, and be fast on the tilt (a sin wave mixed with a cos wave in a funky way) rotation = (amplitude * Mathf.Sin((Time.realtimeSinceStartup * speed) + offset)) * Mathf.Abs(Mathf.Abs(Mathf.Cos((Time.realtimeSinceStartup * speed) + offset)) - 1); slidePower = (rotation / amplitude); //the farther it's tilted, the more powerful the slide if (pTilt) { euler = new Vector3(0, 0, rotation); //if it's a pitch tilt, rotate on z } else { euler = new Vector3(rotation, 0, 0); //if it's a roll tilt, rotate on x } transform.localRotation = Quaternion.Euler(euler); //set the rotation of the floor object if (rotation > 180) { rotation = (360 - rotation) * -1; //if it's over 180, set it to the negative } }
private float GetArcCenterAngle() { return Mathf.Abs(startArc + arcSize / 2); }
public void Run(float move) { _anim.SetFloat("Move", Mathf.Abs(move)); Flip(move); }
public void Execute(RenderContext ctx, KernelData data, ref KernelDefs ports) { data.ProfilerMarker.Begin(); var output = ctx.Resolve(ref ports.Output); output.CopyFrom(ctx.Resolve(in ports.Input)); var weightValue = ctx.Resolve(ports.Weight); if (weightValue > 0f) { var stream = AnimationStreamProvider.Create(data.RigDefinition, output); if (stream.IsNull) { data.ProfilerMarker.End(); return; } // TODO: (sunek) Get a real number! Requires replicating and incrementing the IK weight in update // ikWeight = Mathf.Clamp01(ikWeight + (1 - settings.enterStateEaseIn)); var ikWeight = data.Data.Weight; var settings = data.Data.Settings; var leftToePos = stream.GetLocalToRigTranslation(data.Data.LeftToeIdx); var rightToePos = stream.GetLocalToRigTranslation(data.Data.RightToeIdx); var leftIkOffset = data.Data.ikOffset.x * ikWeight; var rightIkOffset = data.Data.ikOffset.y * ikWeight; leftToePos += new float3(0f, leftIkOffset, 0f); rightToePos += new float3(0f, rightIkOffset, 0f); var leftAnklePos = stream.GetLocalToRigTranslation(data.Data.LeftFootIkIdx); var rightAnklePos = stream.GetLocalToRigTranslation(data.Data.RightFootIkIdx); var leftAnkleRot = stream.GetLocalToRigRotation(data.Data.LeftFootIkIdx); var rightAnkleRot = stream.GetLocalToRigRotation(data.Data.RightFootIkIdx); var leftAnkleIkPos = new float3(leftAnklePos.x, leftAnklePos.y + leftIkOffset, leftAnklePos.z); var rightAnkleIkPos = new float3(rightAnklePos.x, rightAnklePos.y + rightIkOffset, rightAnklePos.z); var hipHeightOffset = (leftIkOffset + rightIkOffset) * 0.5f; var forwardBackBias = (leftIkOffset - rightIkOffset) * settings.weightShiftHorizontal; // TODO: (sunek) Rework weight shift to move towards actual lower foot? hipHeightOffset += Mathf.Abs(leftIkOffset - rightIkOffset) * settings.weightShiftVertical; var standAngle = math.mul(quaternion.AxisAngle(Vector3.up, math.radians(settings.weightShiftAngle)), data.VectorForward); var hipsPosition = stream.GetLocalToRigTranslation(data.Data.HipsIdx); hipsPosition += new float3(standAngle.x * forwardBackBias, hipHeightOffset, standAngle.z * forwardBackBias); stream.SetLocalToRigTranslation(data.Data.HipsIdx, hipsPosition); // Figure out the normal rotation var leftNormalRot = quaternion.identity; var rightNormalRot = quaternion.identity; if (!data.Data.normalLeftFoot.Equals(float3.zero)) { leftNormalRot = quaternion.LookRotationSafe(data.Data.normalLeftFoot, data.VectorForward); rightNormalRot = quaternion.LookRotationSafe(data.Data.normalRightFoot, data.VectorForward); leftNormalRot = math.mul(leftNormalRot, data.OffsetRotation); rightNormalRot = math.mul(rightNormalRot, data.OffsetRotation); } // Clamp normal rotation var leftAngle = Angle(quaternion.identity, leftNormalRot); var rightAngle = Angle(quaternion.identity, rightNormalRot); if (leftAngle > settings.maxFootRotationOffset && settings.maxFootRotationOffset > 0f) { var fraction = settings.maxFootRotationOffset / leftAngle; leftNormalRot = math.nlerp(Quaternion.identity, leftNormalRot, fraction); } if (rightAngle > settings.maxFootRotationOffset && settings.maxFootRotationOffset > 0f) { var fraction = settings.maxFootRotationOffset / rightAngle; rightNormalRot = math.nlerp(Quaternion.identity, rightNormalRot, fraction); } // Apply rotation to ankle var leftToesMatrix = Matrix4x4.TRS(leftToePos, quaternion.identity, data.VectorOne); var rightToesMatrix = Matrix4x4.TRS(rightToePos, quaternion.identity, data.VectorOne); leftNormalRot = math.normalize(leftNormalRot); rightNormalRot = math.normalize(rightNormalRot); leftAnkleRot = math.normalize(leftAnkleRot); rightAnkleRot = math.normalize(rightAnkleRot); var leftToesNormalDeltaMatrix = Matrix4x4.TRS(leftToePos, leftNormalRot, data.VectorOne) * leftToesMatrix.inverse; var rightToesNormalDeltaMatrix = Matrix4x4.TRS(rightToePos, rightNormalRot, data.VectorOne) * rightToesMatrix.inverse; var leftAnkleMatrix = Matrix4x4.TRS(leftAnkleIkPos, leftAnkleRot, data.VectorOne) * leftToesMatrix.inverse; var rightAnkleMatrix = Matrix4x4.TRS(rightAnkleIkPos, rightAnkleRot, data.VectorOne) * rightToesMatrix.inverse; leftAnkleMatrix = leftToesNormalDeltaMatrix * leftAnkleMatrix * leftToesMatrix; rightAnkleMatrix = rightToesNormalDeltaMatrix * rightAnkleMatrix * rightToesMatrix; // Todo:Find a better way to do this? var leftColumn = leftAnkleMatrix.GetColumn(3); leftAnkleIkPos = new float3(leftColumn[0], leftColumn[1], leftColumn[2]); // TODO: (sunek) Is there a slicing syntax instead? var rightColumn = rightAnkleMatrix.GetColumn(3); rightAnkleIkPos = new float3(rightColumn[0], rightColumn[1], rightColumn[2]); leftAnkleRot = math.nlerp(leftAnkleRot, leftAnkleMatrix.rotation, ikWeight); rightAnkleRot = math.nlerp(rightAnkleRot, rightAnkleMatrix.rotation, ikWeight); // Update ik position // TODO: (sunek) Consider combating leg overstretch var leftPosition = math.lerp(leftAnklePos, leftAnkleIkPos, ikWeight); var rightPosition = math.lerp(rightAnklePos, rightAnkleIkPos, ikWeight); stream.SetLocalToRigTranslation(data.Data.LeftFootIkIdx, leftPosition); stream.SetLocalToRigTranslation(data.Data.RightFootIkIdx, rightPosition); stream.SetLocalToRigRotation(data.Data.LeftFootIkIdx, leftAnkleRot); stream.SetLocalToRigRotation(data.Data.RightFootIkIdx, rightAnkleRot); } data.ProfilerMarker.End(); }
void FixedUpdate() { RaycastHit2D hit = Physics2D.BoxCast(this.transform.position, new Vector2(0.4f, 0.1f), 0f, Vector2.down, groundCheckRadius, groundMask); //using this for a bigger and more accurate ground check isTouchingGround = (hit.collider != null) ? true : false; movementInput = Input.GetAxis("Horizontal"); CheckIfStuck(); //Checks if Mario is trying to walk into the wall and get stuck if (GameObject.FindWithTag("Player").transform.position.x < 116f)// level finished { if (!isDead) { if ((playerRigidbody2D.velocity.x > 0 && !isFacingRight) || (playerRigidbody2D.velocity.x < 0 && isFacingRight)) { playerAnimator.SetBool("turning", true); } else { playerAnimator.SetBool("turning", false); } float movementForceMultiplier = Mathf.Max(maxHorizontalSpeed - Mathf.Abs(playerRigidbody2D.velocity.x), 1); playerRigidbody2D.AddForce(new Vector2(movementInput * movementForce * movementForceMultiplier, 0)); playerRigidbody2D.velocity = new Vector2(Mathf.Clamp(playerRigidbody2D.velocity.x, -maxHorizontalSpeed, maxHorizontalSpeed), Mathf.Clamp(playerRigidbody2D.velocity.y, -maxVerticalSpeed, maxVerticalSpeed)); if (Input.GetKeyDown(KeyCode.Space)) { if (isTouchingGround) { //Play Jump sound if (!poweredUp) audioSource.PlayOneShot(smallJumpSound); else audioSource.PlayOneShot(bigJumpSound); isJumping = true; playerRigidbody2D.velocity = new Vector2(playerRigidbody2D.velocity.x, jumpVelocity); jumpTimeCounter = jumpTime; } } if (jumpTimeCounter > 0 && isJumping) if (Input.GetKey(KeyCode.Space)) { jumpTimeCounter -= Time.deltaTime; { playerRigidbody2D.velocity = new Vector2(playerRigidbody2D.velocity.x, jumpVelocity); } } if (Input.GetKeyUp(KeyCode.Space)) { isJumping = false; jumpTimeCounter = 0; } playerAnimator.SetFloat("movementSpeed", Mathf.Abs(playerRigidbody2D.velocity.x)); playerAnimator.SetBool("touchingGround", isTouchingGround); } GameObject.FindWithTag("InvisiblePlayer").GetComponent<SpriteRenderer>().enabled = false; tunTheFirework = true; } else { GameObject.FindWithTag("Player").GetComponent<SpriteRenderer>().enabled = false;// make player invisible and start animation if (tunTheFirework == true)// start firework { GameObject.FindWithTag("InvisiblePlayer").GetComponent<SpriteRenderer>().enabled = true;// make invisible animation player visible audioSource.PlayOneShot(firework);// start firework audio fireworkGameObject.SetActive(true);// make firework activate tunTheFirework = false; } } CheckFlipSpriteOfPlayer();// make it cleaner GameObject.FindWithTag("Player").GetComponent<CapsuleCollider2D>().isTrigger = false;// player wont die } // FixedUpdate
private void FixedUpdate() { float t = (Time.time + offset) * timeScale; Vector2 vectorOffset = new Vector2( Mathf.Sin(t) + Mathf.Cos(t / 2), Mathf.Cos(t * 2) - Mathf.Sin(t) ); if (rigidbody2D != null) { if (rigidbody2D.angularVelocity > 10.0f) { rigidbody2D.AddTorque(-0.1f * 100 * Time.fixedDeltaTime); } else if (rigidbody2D.angularVelocity < -10.0f) { rigidbody2D.AddTorque(0.1f * 100 * Time.fixedDeltaTime); } else { float desiredRot = Mathf.Rad2Deg * (Mathf.Sin(t / 2) * Mathf.Cos(t * 2)) - transform.eulerAngles.z; while (desiredRot > 360.0f) { desiredRot -= 360.0f; } while (desiredRot < 0.0f) { desiredRot += 360.0f; } if (Mathf.Abs(desiredRot - 360.0f) < desiredRot) { desiredRot -= 360.0f; } rigidbody2D.AddTorque((desiredRot > 0.0f ? 0.1f : -0.1f) * 100 * Time.fixedDeltaTime); } var currPos = new Vector2(transform.position.x, transform.position.y); var scale = new Vector2(0.01f, 0.01f); var velocity = (basePosition + vectorOffset - currPos).normalized * scale; if (rigidbody2D.velocity.x > 0.1f) { velocity.x = -0.01f; } else if (rigidbody2D.velocity.x < -0.1f) { velocity.x = 0.01f; } if (rigidbody2D.velocity.y > 10.0f) { velocity.y = -0.01f; } else if (rigidbody2D.velocity.y < -10.0f) { velocity.y = 0.01f; } rigidbody2D.AddForce(velocity * 100 * Time.fixedDeltaTime); } }
void Update() { if(particleSource != null) { transform.position = particleSource.position+new Vector3(0,0,-1); particleSystem.startLifetime = Vector2.Distance(transform.position, transform.parent.position) / Mathf.Abs(mainModule.startSpeed.constant); int numParticlesAlive = particleSystem.GetParticles(particles); float velocity; float distance; // Change only the particles that are alive for (int i = 0; i < numParticlesAlive; ++i) { velocity = particles[i].velocity.magnitude; particles[i].velocity = velocity * (transform.parent.position - particles[i].position).normalized; distance = Vector2.Distance(transform.parent.position, particles[i].position); if(distance > 0.01f) { particles[i].remainingLifetime = distance / velocity; } else { particles[i].remainingLifetime = -1; } } particleSystem.SetParticles(particles, numParticlesAlive); } }
void FixedUpdate() { for (var i = 0; i < allColliders.Count; i++) { DrawBoundingVolume(allColliders[i], Color.green); } collisionInfoText.text = ""; for (int i = 0; i < colliders.Count; ++i) { CustomCollider colliderA = colliders[i]; for (int j = 0; j < immovablecolliders.Count; ++j) { CustomCollider colliderB = immovablecolliders[j]; CustomCollisionInfo collisionInfo; if (CheckCollision(colliderA, colliderB, out collisionInfo)) { Debug.Log(colliderA.gameObject + " collision with " + colliderB.gameObject); collisionInfoText.text += colliderA.gameObject.name + " collision with " + colliderB.gameObject.name + "\n"; float ax = Mathf.Abs(collisionInfo.intersectionSize.x); float ay = Mathf.Abs(collisionInfo.intersectionSize.y); float az = Mathf.Abs(collisionInfo.intersectionSize.z); float sx = colliderA.transform.position.x < colliderB.transform.position.x ? -1.0f : 1.0f; float sy = colliderA.transform.position.y < colliderB.transform.position.y ? -1.0f : 1.0f; float sz = colliderA.transform.position.z < colliderB.transform.position.z ? -1.0f : 1.0f; Vector3 firstCollisionNorm; if (ax <= ay && ax <= az) { // Debug.Log("X"); firstCollisionNorm = colliderB.U().normalized *sx; } else if (ay <= az) { // Debug.Log("Y"); firstCollisionNorm = colliderB.V().normalized *sy; } else { // Debug.Log("Z"); firstCollisionNorm = colliderB.W().normalized *sz; } if (!colliderA.GetComponent <CustomRigidbody>().disablePhysicsInteractions) { var newVel = Vector3.Reflect(colliderA.GetComponent <CustomRigidbody>().currentVelocity.normalized, firstCollisionNorm) * colliderA.GetComponent <CustomRigidbody>().currentVelocity.magnitude *colliderA.bouncieness *(1 - colliderB.frictionCoefficient); newVel = newVel.magnitude < 0.25f ? Vector3.zero : newVel; // colliderA.transform.position += firstCollisionNorm * collisionInfo.intersectionSize.magnitude; if (collisionInfo.intersectionSize.magnitude >= 0.1f) { if (ax <= ay && ax <= az) { colliderA.transform.position += firstCollisionNorm * collisionInfo.intersectionSize.x; } else if (ay <= az) { colliderA.transform.position += firstCollisionNorm * collisionInfo.intersectionSize.y; } else { colliderA.transform.position += firstCollisionNorm * collisionInfo.intersectionSize.z; } } colliderA.GetComponent <CustomRigidbody>().currentVelocity = newVel; } } } for (int j = i + 1; j < colliders.Count; ++j) { CustomCollider colliderB = colliders[j]; CustomCollisionInfo collisionInfo; if (CheckCollision(colliderA, colliderB, out collisionInfo)) { Debug.Log(colliderA.gameObject + " collision with " + colliderB.gameObject); collisionInfoText.text += colliderA.gameObject.name + " collision with " + colliderB.gameObject.name + "\n"; float ax = Mathf.Abs(collisionInfo.intersectionSize.x); float ay = Mathf.Abs(collisionInfo.intersectionSize.y); float az = Mathf.Abs(collisionInfo.intersectionSize.z); float sx = colliderA.transform.position.x < colliderB.transform.position.x ? -1.0f : 1.0f; float sy = colliderA.transform.position.y < colliderB.transform.position.y ? -1.0f : 1.0f; float sz = colliderA.transform.position.z < colliderB.transform.position.z ? -1.0f : 1.0f; Vector3 firstCollisionNorm; if (ax <= ay && ax <= az) { // Debug.Log("X"); firstCollisionNorm = colliderB.W().normalized *sx; } else if (ay <= az) { // Debug.Log("Y"); firstCollisionNorm = colliderB.V().normalized *sy; } else { // Debug.Log("Z"); firstCollisionNorm = colliderB.U().normalized *sz; } // Pulled from Year 2 sphere vs cube simulation assignment float m1, m2, x1, x2; Vector3 v1, v2, v1x, v2x, v1y, v2y, x = (colliderA.transform.position - colliderB.transform.position); var rbA = colliderA.GetComponent <CustomRigidbody>(); var rbB = colliderB.GetComponent <CustomRigidbody>(); x.Normalize(); v1 = rbA.currentVelocity; x1 = Vector3.Dot(x, v1); v1x = x * x1; v1y = v1 - v1x; m1 = rbA.mass; x = x * -1; v2 = rbB.currentVelocity; x2 = Vector3.Dot(x, v2); v2x = x * x2; v2y = v2 - v2x; m2 = rbB.mass; if (!colliderA.GetComponent <CustomRigidbody>().disablePhysicsInteractions) { rbA.currentVelocity = (v1x * (m1 - m2) / (m1 + m2) + v2x * (2 * m2) / (m1 + m2) + v1y); } if (!colliderB.GetComponent <CustomRigidbody>().disablePhysicsInteractions) { rbB.currentVelocity = (v1x * (2 * m1) / (m1 + m2) + v2x * (m2 - m1) / (m1 + m2) + v2y); } /*continue; * * if (colliderA.GetComponent<CustomRigidbody>()) * { * var directionA = colliderA.GetComponent<CustomRigidbody>().currentVelocity.normalized; * var directionB = colliderB.GetComponent<CustomRigidbody>().currentVelocity.normalized; * var newDir = (directionA - directionB).normalized; * var speed = colliderA.GetComponent<CustomRigidbody>().currentVelocity.magnitude + * colliderB.GetComponent<CustomRigidbody>().currentVelocity.magnitude; * * var newVel = * Vector3.Reflect(newDir, -firstCollisionNorm) * speed * colliderA.bouncieness * colliderB.bouncieness; * if (colliderB.GetComponent<CustomRigidbody>()) * newVel *= colliderB.GetComponent<CustomRigidbody>().currentVelocity.magnitude > 1 ? colliderB.GetComponent<CustomRigidbody>().currentVelocity.magnitude : 1; * newVel = newVel.magnitude < 0.25f ? Vector3.zero : newVel; * // colliderA.transform.position += firstCollisionNorm*collisionInfo.intersectionSize.magnitude; * if (collisionInfo.intersectionSize.magnitude >= 0.1f) * { * if (ax <= ay && ax <= az) * colliderA.transform.position += firstCollisionNorm * collisionInfo.intersectionSize.x; * else if (ay <= az) * colliderA.transform.position += firstCollisionNorm * collisionInfo.intersectionSize.y; * else * colliderA.transform.position += firstCollisionNorm * collisionInfo.intersectionSize.z; * } * * colliderA.GetComponent<CustomRigidbody>().currentVelocity = newVel; * } * if (colliderB.GetComponent<CustomRigidbody>()) * { * var directionA = colliderA.GetComponent<CustomRigidbody>().currentVelocity.normalized; * var directionB = colliderB.GetComponent<CustomRigidbody>().currentVelocity.normalized; * var newDir = (directionA).normalized; * var speed = colliderA.GetComponent<CustomRigidbody>().currentVelocity.magnitude + * colliderB.GetComponent<CustomRigidbody>().currentVelocity.magnitude; * * var newVel = * Vector3.Reflect(newDir, firstCollisionNorm) * speed * colliderA.bouncieness * colliderB.bouncieness; * if (colliderA.GetComponent<CustomRigidbody>()) * newVel *= colliderA.GetComponent<CustomRigidbody>().currentVelocity.magnitude > 1 ? colliderA.GetComponent<CustomRigidbody>().currentVelocity.magnitude : 1; * newVel = newVel.magnitude < 0.25f ? Vector3.zero : newVel; * // colliderB.transform.position += -firstCollisionNorm * collisionInfo.intersectionSize.magnitude; * if (collisionInfo.intersectionSize.magnitude >= 0.1f) * { * if (ax <= ay && ax <= az) * colliderB.transform.position += -firstCollisionNorm * collisionInfo.intersectionSize.x; * else if (ay <= az) * colliderB.transform.position += -firstCollisionNorm * collisionInfo.intersectionSize.y; * else * colliderB.transform.position += -firstCollisionNorm * collisionInfo.intersectionSize.z; * } * * colliderB.GetComponent<CustomRigidbody>().currentVelocity = newVel; * }*/ } } } }
void FixedUpdate() { // speed of car speed = myRigidbody.velocity.magnitude * 2.7f; if (speed < lastSpeed - 10 && slip < 10) { slip = lastSpeed / 15; } lastSpeed = speed; if (slip2 != 0.0f) { slip2 = Mathf.MoveTowards(slip2, 0.0f, 0.1f); } myRigidbody.centerOfMass = carSetting.shiftCentre; if (vehicleMode == VehicleMode.Player && GameUI.manage.gameStarted) { if (AIControl.manage.controlMode == ControlMode.Simple) { accel = 0; brake = false; shift = false; if (carWheels.wheels.frontWheelDrive || carWheels.wheels.backWheelDrive) { steer = Input.GetAxis("Horizontal"); accel = Input.GetAxis("Vertical"); brake = Input.GetButton("Jump"); shift = Input.GetKey(KeyCode.LeftShift) | Input.GetKey(KeyCode.RightShift); } if (!carSetting.automaticGear) { if (Input.GetKeyDown("page up")) { ShiftUp(); } if (Input.GetKeyDown("page down")) { ShiftDown(); } } } else if (AIControl.manage.controlMode == ControlMode.Mobile) { if (accelFwd != 0) { accel = accelFwd; } else { accel = accelBack; } if (GameUI.manage.panels.gamePlay.buttonsUI.activeSelf) { steer = Mathf.MoveTowards(steer, steerAmount, 0.1f); } else if (GameUI.manage.panels.gamePlay.accelUI.activeSelf) { steer = Mathf.MoveTowards(steer, Input.acceleration.x * 2.0f, 0.4f); } } } else if (vehicleMode == VehicleMode.AICar && GameUI.manage.gameStarted) { shift = false; if (!GameUI.manage.gameFinished) { vehicleMode = VehicleMode.Player; } steer = AIVehicle.AISteer; accel = AIVehicle.AIAccel; brake = AIVehicle.AIBrake; } else { steer = 0; shift = false; if (vehicleMode == VehicleMode.Player) { if (AIControl.manage.controlMode == ControlMode.Simple) { accel = Input.GetAxis("Vertical"); } else { accel = accelFwd; } } else { accel = 1.0f; } } if (!carWheels.wheels.frontWheelDrive && !carWheels.wheels.backWheelDrive) { accel = 0.0f; } if (carSetting.carSteer) { carSetting.carSteer.localEulerAngles = new Vector3(steerCurAngle.x, steerCurAngle.y, steerCurAngle.z + (steer * -120.0f)); } if (carSetting.automaticGear && (currentGear == 1) && (accel < 0.0f)) { if (speed < 5.0f) { ShiftDown(); } } else if (carSetting.automaticGear && (currentGear == 0) && (accel > 0.0f)) { if (speed < 5.0f) { ShiftUp(); } } else if (carSetting.automaticGear && (motorRPM > carSetting.shiftUpRPM) && (accel > 0.0f) && speed > 10.0f && !brake) { ShiftUp(); } else if (carSetting.automaticGear && (motorRPM < carSetting.shiftDownRPM) && (currentGear > 1)) { ShiftDown(); } if (speed < 1.0f) { Backward = true; } if (currentGear == 0 && Backward == true) { carSetting.shiftCentre.z = -accel / -5; if (speed < carSetting.gears[0] * -10) { accel = -accel; } } else { Backward = false; if (currentGear > 0) { carSetting.shiftCentre.z = -(accel / currentGear) / -5; } } carSetting.shiftCentre.x = -Mathf.Clamp(steer * (speed / 100), -0.03f, 0.03f); // Brake Lights foreach (Light brakeLight in carLights.brakeLights) { if (brake || accel < 0 || speed < 1.0f) { brakeLight.intensity = Mathf.MoveTowards(brakeLight.intensity, 8, 0.5f); } else { brakeLight.intensity = Mathf.MoveTowards(brakeLight.intensity, 0, 0.5f); } brakeLight.enabled = brakeLight.intensity == 0 ? false : true; } // Reverse Lights foreach (Light WLight in carLights.reverseLights) { if (speed > 2.0f && currentGear == 0) { WLight.intensity = Mathf.MoveTowards(WLight.intensity, 8, 0.5f); } else { WLight.intensity = Mathf.MoveTowards(WLight.intensity, 0, 0.5f); } WLight.enabled = WLight.intensity == 0 ? false : true; } wantedRPM = (5500.0f * accel) * 0.1f + wantedRPM * 0.9f; float rpm = 0.0f; int motorizedWheels = 0; bool floorContact = false; int currentWheel = 0; if (currentGear > 0) { myRigidbody.AddRelativeTorque(0, steer * 10000, 0); } else { myRigidbody.AddRelativeTorque(0, -steer * 10000, 0); } foreach (WheelComponent w in wheels) { WheelHit hit; WheelCollider col = w.collider; if (w.drive) { if (!NeutralGear && brake && currentGear < 2) { rpm += accel * carSetting.idleRPM; } else { if (!NeutralGear) { rpm += col.rpm; } else { rpm += (carSetting.idleRPM * accel); } } motorizedWheels++; } if (brake || accel < 0.0f) { if ((accel < 0.0f) || (brake && (w == wheels[2] || w == wheels[3]))) { if (brake && (accel > 0.0f)) { slip = Mathf.Lerp(slip, 5.0f, accel * 0.01f); } else if (speed > 1.0f) { slip = Mathf.Lerp(slip, 1.0f, 0.002f); } else { slip = Mathf.Lerp(slip, 1.0f, 0.02f); } wantedRPM = 0.0f; col.brakeTorque = carSetting.brakePower; w.rotation = w_rotate; } } else { col.brakeTorque = accel == 0 || NeutralGear ? col.brakeTorque = 1000 : col.brakeTorque = 0; slip = speed > 0.0f ? (speed > 100 ? slip = Mathf.Lerp(slip, 1.0f + Mathf.Abs(steer), 0.02f) : slip = Mathf.Lerp(slip, 1.5f, 0.02f)) : slip = Mathf.Lerp(slip, 0.01f, 0.02f); w_rotate = w.rotation; } WheelFrictionCurve fc = col.forwardFriction; fc.asymptoteValue = 5000.0f; fc.extremumSlip = 2.0f; fc.asymptoteSlip = 20.0f; fc.stiffness = carSetting.stiffness / (slip + slip2); col.forwardFriction = fc; fc = col.sidewaysFriction; fc.stiffness = carSetting.stiffness / (slip + slip2); fc.extremumSlip = 0.3f + Mathf.Abs(steer); col.sidewaysFriction = fc; if (shift && (currentGear > 1 && speed > 50.0f) && shifmotor) { if (powerShift == 0) { shifmotor = false; } powerShift = Mathf.MoveTowards(powerShift, 0.0f, Time.deltaTime * 10.0f); carSounds.nitro.volume = Mathf.Lerp(carSounds.nitro.volume, 1.0f, Time.deltaTime * 10.0f); if (!carSounds.nitro.isPlaying) { carSounds.nitro.GetComponent <AudioSource>().Play(); } shifting = true; curTorque = powerShift > 0 ? carSetting.shiftPower / slipRate : carSetting.carPower / slipRate; carParticles.shiftParticle1.emissionRate = Mathf.Lerp(carParticles.shiftParticle1.emissionRate, powerShift > 0 ? 50 : 0, Time.deltaTime * 10.0f); carParticles.shiftParticle2.emissionRate = Mathf.Lerp(carParticles.shiftParticle2.emissionRate, powerShift > 0 ? 50 : 0, Time.deltaTime * 10.0f); } else { if (powerShift > 20) { shifmotor = true; } carSounds.nitro.volume = Mathf.MoveTowards(carSounds.nitro.volume, 0.0f, Time.deltaTime * 2.0f); if (carSounds.nitro.volume == 0) { carSounds.nitro.Stop(); } shifting = false; powerShift = Mathf.MoveTowards(powerShift, 100.0f, Time.deltaTime * 5.0f); curTorque = carSetting.carPower / slipRate; carParticles.shiftParticle1.emissionRate = Mathf.Lerp(carParticles.shiftParticle1.emissionRate, 0, Time.deltaTime * 10.0f); carParticles.shiftParticle2.emissionRate = Mathf.Lerp(carParticles.shiftParticle2.emissionRate, 0, Time.deltaTime * 10.0f); } w.rotation = Mathf.Repeat(w.rotation + Time.deltaTime * col.rpm * 360.0f / 60.0f, 360.0f); w.rotation2 = Mathf.Lerp(w.rotation2, col.steerAngle, 0.1f); w.wheel.localRotation = Quaternion.Euler(w.rotation, w.rotation2, 0.0f); Vector3 lp = w.wheel.localPosition; if (col.GetGroundHit(out hit)) { if (carParticles.brakeParticlePerfab) { if (Particle[currentWheel] == null) { Particle[currentWheel] = Instantiate(carParticles.brakeParticlePerfab, w.wheel.position, Quaternion.identity) as GameObject; Particle[currentWheel].name = "WheelParticle"; Particle[currentWheel].transform.parent = transform.transform; Particle[currentWheel].AddComponent <AudioSource>(); Particle[currentWheel].GetComponent <AudioSource>().maxDistance = 50; Particle[currentWheel].GetComponent <AudioSource>().spatialBlend = 1; Particle[currentWheel].GetComponent <AudioSource>().dopplerLevel = 5; Particle[currentWheel].GetComponent <AudioSource>().rolloffMode = AudioRolloffMode.Custom; Particle[currentWheel].GetComponent <AudioSource>().outputAudioMixerGroup = carSounds.brakeAudioMixer; } var pc = Particle[currentWheel].GetComponent <ParticleSystem>(); bool WGrounded = false; slipRate = 1.0f; for (int i = 0; i < carSetting.hitGround.Length; i++) { if (hit.collider.CompareTag(carSetting.hitGround[i].tag)) { WGrounded = carSetting.hitGround[i].grounded; if ((brake || Mathf.Abs(hit.sidewaysSlip) > 0.3f) && speed > 1) { Particle[currentWheel].GetComponent <AudioSource>().clip = carSetting.hitGround[i].brakeSound; } else if (Particle[currentWheel].GetComponent <AudioSource>().clip != carSetting.hitGround[i].groundSound && !Particle[currentWheel].GetComponent <AudioSource>().isPlaying) { Particle[currentWheel].GetComponent <AudioSource>().clip = carSetting.hitGround[i].groundSound; } Particle[currentWheel].GetComponent <ParticleSystem>().startColor = carSetting.hitGround[i].brakeColor; } } if (WGrounded) { GameUI.manage.carPenalty = true; if (speed > 70) { w.collider.brakeTorque = 2000; } } else { GameUI.manage.carPenalty = false; } if (WGrounded && speed > 5 && !brake) { pc.enableEmission = true; pc.emissionRate = Mathf.Lerp(pc.emissionRate, 100.0f, 0.1f); GameUI.manage.driftAmount = 0; GameUI.manage.canDrift = false; Particle[currentWheel].GetComponent <AudioSource>().volume = 0.5f; if (!Particle[currentWheel].GetComponent <AudioSource>().isPlaying) { Particle[currentWheel].GetComponent <AudioSource>().Play(); } } else if ((brake || Mathf.Abs(hit.sidewaysSlip) > 0.2f) && speed > 1) { if ((accel < 0.0f) || ((brake || Mathf.Abs(hit.sidewaysSlip) > 0.2f) && (w == wheels[2] || w == wheels[3]))) { pc.emissionRate = Mathf.Lerp(pc.emissionRate, 100.0f, 0.5f); pc.enableEmission = true; if (!Particle[currentWheel].GetComponent <AudioSource>().isPlaying) { Particle[currentWheel].GetComponent <AudioSource>().Play(); } Particle[currentWheel].GetComponent <AudioSource>().volume = 10; if (speed > 20.0f && Mathf.Abs(hit.sidewaysSlip) > 0.1f && GameUI.manage.canDrift) { GameUI.manage.driftAmount += 1; } else { GameUI.manage.driftAmount = 0; GameUI.manage.canDrift = false; } } } else { pc.emissionRate = Mathf.Lerp(pc.emissionRate, 0.0f, 0.05f); if (pc.emissionRate < 2.0f) { GameUI.manage.driftAmount = 0; GameUI.manage.canDrift = false; pc.enableEmission = false; } Particle[currentWheel].GetComponent <AudioSource>().volume = Mathf.Lerp(Particle[currentWheel].GetComponent <AudioSource>().volume, 0, Time.deltaTime * 10.0f); } } lp.y -= Vector3.Dot(w.wheel.position - hit.point, transform.TransformDirection(0, 1, 0) / transform.lossyScale.x) - (col.radius); lp.y = Mathf.Clamp(lp.y, -10.0f, w.pos_y); floorContact = floorContact || (w.drive); } else { if (Particle[currentWheel] != null) { var pc = Particle[currentWheel].GetComponent <ParticleSystem>(); pc.emissionRate = Mathf.Lerp(pc.emissionRate, 0.0f, 0.1f); if (pc.emissionRate < 2.0f) { GameUI.manage.driftAmount = 0; GameUI.manage.canDrift = false; pc.enableEmission = false; } } lp.y = w.startPos.y - carWheels.setting.Distance; myRigidbody.AddForce(Vector3.down * 10000); } currentWheel++; w.wheel.localPosition = lp; } if (motorizedWheels > 1) { rpm = rpm / motorizedWheels; } motorRPM = 0.95f * motorRPM + 0.05f * Mathf.Abs(rpm * carSetting.gears[currentGear]); if (motorRPM > 5500.0f) { motorRPM = 5200.0f; } int index = (int)(motorRPM / efficiencyTableStep); if (index >= efficiencyTable.Length) { index = efficiencyTable.Length - 1; } if (index < 0) { index = 0; } float newTorque = curTorque * carSetting.gears[currentGear] * efficiencyTable[index]; foreach (WheelComponent w in wheels) { WheelCollider col = w.collider; if (w.drive) { if (Mathf.Abs(col.rpm) > Mathf.Abs(wantedRPM)) { col.motorTorque = 0; } else { float curTorqueCol = col.motorTorque; if (!brake && accel != 0 && NeutralGear == false) { if ((speed < carSetting.LimitForwardSpeed && currentGear > 0) || (speed < carSetting.LimitBackwardSpeed && currentGear == 0)) { col.motorTorque = curTorqueCol * 0.9f + newTorque * 1.0f; } else { col.motorTorque = 0; col.brakeTorque = 0; } } else { col.motorTorque = 0; } } } if (brake || slip2 > 2.0f) { col.steerAngle = Mathf.Lerp(col.steerAngle, steer * w.maxSteer, 0.05f); } else { float SteerAngle = Mathf.Clamp(speed / carSetting.maxSteerAngle, 1.0f, carSetting.maxSteerAngle); col.steerAngle = steer * (w.maxSteer / SteerAngle); } } // calculate pitch (keep it within reasonable bounds) Pitch = Mathf.Clamp(1.2f + ((motorRPM - carSetting.idleRPM) / (carSetting.shiftUpRPM - carSetting.idleRPM)), 1.0f, 10.0f); shiftTime = Mathf.MoveTowards(shiftTime, 0.0f, 0.1f); if (Pitch == 1) { carSounds.IdleEngine.volume = Mathf.Lerp(carSounds.IdleEngine.volume, 1.0f, 0.1f); carSounds.LowEngine.volume = Mathf.Lerp(carSounds.LowEngine.volume, 0.5f, 0.1f); carSounds.HighEngine.volume = Mathf.Lerp(carSounds.HighEngine.volume, 0.0f, 0.1f); } else { carSounds.IdleEngine.volume = Mathf.Lerp(carSounds.IdleEngine.volume, 1.8f - Pitch, 0.1f); if ((Pitch > PitchDelay || accel > 0) && shiftTime == 0.0f) { carSounds.LowEngine.volume = Mathf.Lerp(carSounds.LowEngine.volume, 0.0f, 0.2f); carSounds.HighEngine.volume = Mathf.Lerp(carSounds.HighEngine.volume, 1.0f, 0.1f); } else { carSounds.LowEngine.volume = Mathf.Lerp(carSounds.LowEngine.volume, 0.5f, 0.1f); carSounds.HighEngine.volume = Mathf.Lerp(carSounds.HighEngine.volume, 0.0f, 0.2f); } carSounds.HighEngine.pitch = Pitch; carSounds.LowEngine.pitch = Pitch; PitchDelay = Pitch; } }
private byte EaseToward(byte from, byte to, int amount) { if (Mathf.Abs(from - to) < amount) return to; return (byte)(from + (to > from ? amount : -amount)); }
static bool Differs(float a, float b) { return(Mathf.Abs(a - b) > 0.0001f); }
// Update is called once per frame void Update() { Direction = Vector2.zero; //Reset per frame //フレーム毎にリセット #if !UNITY_EDITOR && (UNITY_ANDROID || UNITY_IOS) //Only platforms you want to obtain with touch. //タッチで取得したいプラットフォームのみ if (Input.touchCount == 1) //Multiple fingers are impossible (because there is a possibility of pinching in case of two or more fingers). //複数の指は不可とする(※2つ以上の指の場合はピンチの可能性もあるため) #endif { if (!pressing && Input.GetMouseButtonDown(0)) //When pressed (left click / touch can be acquired). //押したとき(左クリック/タッチが取得できる) { startPos = Input.mousePosition; if (validArea.xMin * Screen.width <= startPos.x && startPos.x <= validArea.xMax * Screen.width && validArea.yMin * Screen.height <= startPos.y && startPos.y <= validArea.yMax * Screen.height) //Within recognition area //認識エリア内 { pressing = true; limitTime = Time.time + timeout; } } else if (pressing && Input.GetMouseButtonUp(0)) //Only when it is already pressed (Note that this function can not distinguish which finger when touching 2 or more). //既に押されているときのみ(※この関数は2つ以上タッチの場合、どの指か判別できないので注意) { pressing = false; if (Time.time < limitTime) //Recognize before time limit //時間制限前なら認識 { endPos = Input.mousePosition; Vector2 dist = endPos - startPos; float dx = Mathf.Abs(dist.x); float dy = Mathf.Abs(dist.y); float requiredPx = widthReference ? Screen.width * validWidth : Screen.height * validWidth; if (dy < dx) //Recognized as horizontal direction //横方向として認識 { if (requiredPx < dx) //Recognize if it exceeds length //長さを超えていたら認識 { Direction = Mathf.Sign(dist.x) < 0 ? Vector2.left : Vector2.right; } } else //Recognized as vertical direction //縦方向として認識 { if (requiredPx < dy) //Recognize if it exceeds length //長さを超えていたら認識 { Direction = Mathf.Sign(dist.y) < 0 ? Vector2.down : Vector2.up; } } if (Direction != Vector2.zero) { if (OnSwipe != null) { OnSwipe.Invoke(Direction); } } } } } #if !UNITY_EDITOR && (UNITY_ANDROID || UNITY_IOS) //タッチで取得したいプラットフォームのみ else //Invalid it when there is not one touch (since there is also a possibility of pinching in case of two or more fingers). //タッチが1つでないときは無効にする(※2つ以上の指の場合はピンチの可能性もあるため) { pressing = false; } #endif }
/// <inheritdoc /> public int GetHashCode(object obj) { return(Mathf.Abs(SourceName.GetHashCode())); }
public float NormalizedReputationDifference(int otherRep) { int difference = Mathf.Abs(FinalReputation - otherRep); return((float)difference / (float)Globals.MaxReputation); }
protected override bool CanIncreaseVelocity(float maxSpeed) => Mathf.Abs(physicalProperties.targetVelocity.x) < maxSpeed;