/// <summary> /// Awake is called when the script instance is being loaded. /// </summary> private void Awake() { animator = GetComponent <Animator>(); hipsTransform = animator.GetBoneTransform(HumanBodyBones.Hips); hipsTransformRigid = hipsTransform.GetComponent <Rigidbody>(); controller = GetComponent <IController>(); rigidbodyComponents = new List <RigidbodyComponent>(); transformComponents = new List <TransformComponent>(); Rigidbody[] rigidbodies = GetComponentsInChildren <Rigidbody>(true); for (int i = 0, length = rigidbodies.Length; i < length; i++) { Rigidbody rigid = rigidbodies[i]; if (rigid.transform == transform) { continue; } RigidbodyComponent rigidCompontnt = new RigidbodyComponent(rigid); rigidbodyComponents.Add(rigidCompontnt); } Transform[] array = GetComponentsInChildren <Transform>(); for (int i = 0, length = array.Length; i < length; i++) { Transform t = array[i]; TransformComponent trComp = new TransformComponent(t); transformComponents.Add(trComp); } }
private void ActivateRagdollParts(bool activate) { controller.ControllerEnabled(!activate); for (int i = 0, length = rigidbodyComponents.Count; i < length; i++) { RigidbodyComponent rigidbody = rigidbodyComponents[i]; Collider partColider = rigidbody.GetRigidBody().GetComponent <Collider>(); if (partColider == null) { const string colliderNodeSufix = "_ColliderRotator"; string childName = rigidbody.GetRigidBody().name + colliderNodeSufix; Transform transform = rigidbody.GetRigidBody().transform.Find(childName); partColider = transform.GetComponent <Collider>(); } partColider.isTrigger = !activate; if (activate) { rigidbody.GetRigidBody().isKinematic = false; StartCoroutine(FixTransformAndEnableJoint(rigidbody)); } else { rigidbody.GetRigidBody().isKinematic = true; } } }
public override void Start() { // creates a subentity for the light lightEntity = new Entity(); lightSprite = lightEntity.GetOrCreate <SpriteComponent>(); lightSprite.SpriteProvider = new SpriteFromSheet() { Sheet = robotSpriteSheet, CurrentFrame = 1, }; lightSprite.Enabled = false; lightPhysics = lightEntity.GetOrCreate <RigidbodyComponent>(); lightPhysics.ColliderShapes.Add(new BoxColliderShapeDesc { Is2D = true, Size = new Vector3(0.3f, 0.4f, 0), }); lightPhysics.RigidBodyType = RigidBodyTypes.Kinematic; // Reacts with light switches lightPhysics.CanCollideWith = CollisionFilterGroupFlags.CustomFilter1; lightPhysics.CollisionGroup = CollisionFilterGroups.CustomFilter1; lightPhysics.Enabled = false; Entity.AddChild(lightEntity); EnabledState = false; }
public override async Task Execute() { sensor = Entity.FindChild("AoESensor").Get <RigidbodyComponent>(); explodeSound = Entity.Get <AudioEmitterComponent>()["Explode"]; await base.Execute(); }
protected Vector3 ReferenceRigidbodyDisplacement(Vector3 position, RigidbodyComponent referenceRigidbody) { if (referenceRigidbody == null) { return(Vector3.zero); } Vector3 initialPosition = position; Quaternion deltaRotation = referenceRigidbody.DesiredRotation * Quaternion.Inverse(referenceRigidbody.Rotation); Vector3 centerToCharacter = position - referenceRigidbody.Position; Vector3 rotatedCenterToCharacter = deltaRotation * centerToCharacter; if (rotateForwardDirection) { Vector3 up = Up; Forward = deltaRotation * Forward; Up = up; } Vector3 finalPosition = referenceRigidbody.DesiredPosition + rotatedCenterToCharacter; return(finalPosition - initialPosition); }
public override void Start() { base.Start(); _rigidbody = Entity.Get <RigidbodyComponent>(); VirtualButtonGroup b1, b2; Input.VirtualButtonConfigSet = new VirtualButtonConfigSet { new VirtualButtonConfig { new VirtualButtonBinding("Horizontal", b1 = new VirtualButtonGroup { new VirtualButtonTwoWay(VirtualButton.Keyboard.Left, VirtualButton.Keyboard.Right), VirtualButton.GamePad.LeftThumbAxisX, new VirtualButtonTwoWay(VirtualButton.Keyboard.A, VirtualButton.Keyboard.D) }), new VirtualButtonBinding("Vertical", b2 = new VirtualButtonGroup { new VirtualButtonTwoWay(VirtualButton.Keyboard.Down, VirtualButton.Keyboard.Up), VirtualButton.GamePad.LeftThumbAxisY, new VirtualButtonTwoWay(VirtualButton.Keyboard.S, VirtualButton.Keyboard.W) }) } }; b1.IsDisjunction = true; b2.IsDisjunction = true; }
public sealed override async Task Execute() { //Make sure that it's possible to instantly swap this out with a more efficient variant! //(Actually, I have no clue how efficient it is to have a bazillion colliders) var trigger = new RigidbodyComponent() { IsTrigger = true, ProcessCollisions = true, CanCollideWith = CollisionFilterGroupFlags.CharacterFilter, ColliderShape = new SphereColliderShape(false, InteractionRadius), IsKinematic = true }; Entity.Add(trigger); while (Game.IsRunning) { Collision collision = await trigger.NewCollision(); var otherCollider = (trigger == collision.ColliderA) ? collision.ColliderB : collision.ColliderA; if (otherCollider.Entity.Get <CharacterComponent>() != null) { StartInteraction(); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed collision.Ended().ContinueWith((_) => EndInteraction()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } } }
/// <inheritdoc/> public Constraint Build(RigidbodyComponent bodyA, RigidbodyComponent bodyB) { var axisA = Vector3.UnitX; AxisInA.Rotate(ref axisA); var axisB = Vector3.UnitX; AxisInA.Rotate(ref axisB); var hinge = bodyB == null ? Simulation.CreateHingeConstraint(bodyA, PivotInA, axisA, UseReferenceFrameA) : Simulation.CreateHingeConstraint(bodyA, PivotInA, axisA, bodyB, PivotInB, axisB, UseReferenceFrameA); if (Limit.SetLimit) { hinge.SetLimit(Limit.LowerLimit, Limit.UpperLimit); } if (Motor.EnableMotor) { hinge.EnableAngularMotor(Motor.EnableMotor, Motor.TargetVelocity, Motor.MaxMotorImpulse); } return(hinge); }
public static void SpawnPrefabModel(this ScriptComponent script, Prefab source, Entity attachEntity, Matrix localMatrix, Vector3 forceImpulse) { if (source == null) { return; } // Clone System.Collections.Generic.List <Entity> spawnedEntities = source.Instantiate(); // Add foreach (Entity prefabEntity in spawnedEntities) { prefabEntity.Transform.UpdateLocalMatrix(); Matrix entityMatrix = prefabEntity.Transform.LocalMatrix * localMatrix; entityMatrix.Decompose(out prefabEntity.Transform.Scale, out prefabEntity.Transform.Rotation, out prefabEntity.Transform.Position); if (attachEntity != null) { attachEntity.AddChild(prefabEntity); } else { script.SceneSystem.SceneInstance.RootScene.Entities.Add(prefabEntity); } RigidbodyComponent physComp = prefabEntity.Get <RigidbodyComponent>(); if (physComp != null) { physComp.ApplyImpulse(forceImpulse); } } }
public override void Start() { simulation = this.GetSimulation(); simulation.Gravity = new Vector3(0, -9, 0); cubeRigidBody = cube.Get <RigidbodyComponent>(); cubeRigidBody.CanSleep = false; sphereRigidBody = sphere.Get <RigidbodyComponent>(); sphereRigidBody.CanSleep = false; // Create the UI constraintNameBlock = new TextBlock { Font = Font, TextSize = 55, TextColor = Color.White, }; constraintNameBlock.SetCanvasPinOrigin(new Vector3(0.5f, 0.5f, 0)); constraintNameBlock.SetCanvasRelativePosition(new Vector3(0.5f, 0.93f, 0)); Entity.Get <UIComponent>().RootElement = new Canvas { Children = { constraintNameBlock, CreateButton("Next Constraint",Font, 1), CreateButton("Last Constraint",Font, -1) } }; // Create and initialize constraint constraintsList.Add(CreatePoint2PointConstraint); constraintsList.Add(CreateHingeConstraint); constraintsList.Add(CreateGearConstraint); constraintsList.Add(CreateSliderConstraint); constraintsList.Add(CreateConeTwistConstraint); constraintsList.Add(CreateGeneric6DoFConstraint); constraintsList[constraintIndex](); //Add a script for the slider constraint, to apply an impulse on collision cubeRigidBody.ProcessCollisions = true; Script.AddTask(async() => { while (Game.IsRunning) { var collision = await cubeRigidBody.NewCollision(); if (!(currentConstraint is SliderConstraint)) { continue; } if (collision.ColliderA != sphereRigidBody && collision.ColliderB != sphereRigidBody) { continue; } sphereRigidBody.LinearVelocity = Vector3.Zero; //clear any existing velocity sphereRigidBody.ApplyImpulse(new Vector3(-25, 0, 0)); //fire impulse } }); }
// Start is called before the first frame update public override void Start() { rb = Entity.Get <RigidbodyComponent>(); // stop rotating Entity.Remove <Turn>(); Entity.Transform.WorldMatrix.TranslationVector = new Vector3(-30, 0, 0); }
public override void UpdateKinematicActor(float dt) { Vector3 position = RigidbodyComponent.Position; Quaternion rotation = RigidbodyComponent.Rotation; movementAction.Tick(dt, ref position); rotationAction.Tick(dt, ref position, ref rotation); //Debug.Log(position+" "+rotation); RigidbodyComponent.SetPositionAndRotation(position, rotation); }
void UpdateRolling() { if (IsGrounded) { float accelMult = 1 - Mathf.Clamp01(velocitySqr / (Rolling.RollSpeed * Rolling.RollSpeed)); RigidbodyComponent.AddForce(worldInputDirection * accelMult * Rolling.RollAcceleration, ForceMode.Acceleration); } RollTimer -= Time.deltaTime; IsRolling = RollTimer > 0; }
public void UpdateSystem(BulletComponent bullet, RigidbodyComponent rigidbody) { bullet.timeAlive += Time.fixedDeltaTime; rigidbody.velocity = bullet.transform.up * bulletSpeed; if (bullet.timeAlive > bulletLife) { bullet.entity.Destroy(); } }
public override void Start() { physics = Entity.Get <RigidbodyComponent>(); robotLight = Entity.Get <RobotLight>(); robotHolder = Entity.Get <RobotHolder>(); robotLaser = Entity.Get <RobotLaser>(); spriteProvider = Entity.Get <SpriteComponent>().SpriteProvider as SpriteFromSheet; robotLight.UpdateTransform(direction); UpdateSprite(direction); }
void FixedUpdate() { RigidbodyComponent.MovePosition(RigidbodyComponent.position + _direction * (_bulletSpeed * Time.fixedDeltaTime)); if (RigidbodyComponent.position.x > GlobalConstants.MapSize || RigidbodyComponent.position.x < -1.0f || RigidbodyComponent.position.y > GlobalConstants.MapSize || RigidbodyComponent.position.y < -1.0f) { Destroy(gameObject); return; } }
/// <inheritdoc/> public Constraint Build(RigidbodyComponent bodyA, RigidbodyComponent bodyB) { var frameA = Matrix.Translation(PivotInA); var frameB = Matrix.Translation(PivotInB); var point2point = (bodyB == null ? Simulation.CreateConstraint(ConstraintTypes.Point2Point, bodyA, frameA) : Simulation.CreateConstraint(ConstraintTypes.Point2Point, bodyA, bodyB, frameA, frameB) ) as Point2PointConstraint; return(point2point); }
public override void Start() { try { rb = Entity.Get <RigidbodyComponent>(); collisionNumber = CountCollision(); } catch (Exception) { throw new Exception("A conductive object must have a Rigidbody component"); } }
public void SetReferenceRigidbody(Transform target) { if (target == null) { attachedRigidbody = null; return; } RigidbodyComponent rigidbodyComponent = groundRigidbodyComponents.GetOrRegisterValue <Transform, RigidbodyComponent>(target); attachedRigidbody = rigidbodyComponent; }
void FixedUpdate() { float dt = Time.deltaTime; Vector3 position = RigidbodyComponent.Position; Quaternion rotation = RigidbodyComponent.Rotation; movementAction.Tick(dt, ref position); rotationAction.Tick(dt, ref position, ref rotation); RigidbodyComponent.MoveAndRotate(position, rotation); }
public void AddExtraMove(Vector3 move) { if (IsRagdolled()) { Vector3 airMove = new Vector3(move.x * AirSpeed, 0f, move.z * AirSpeed); for (int i = 0, length = rigidbodyComponents.Count; i < length; i++) { RigidbodyComponent rigidbodyComponent = rigidbodyComponents[i]; rigidbodyComponent.GetRigidBody().AddForce(airMove / 100f, ForceMode.VelocityChange); } } }
void InterpolateRigidbodyComponent(RigidbodyComponent rigidbodyComponent) { Vector3 startPosition = rigidbodyComponent.transform.position; Vector3 endPosition = rigidbodyComponent.Position; Quaternion startRotation = rigidbodyComponent.transform.rotation; Quaternion endRotation = rigidbodyComponent.Rotation; rigidbodyComponent.Position = startPosition; rigidbodyComponent.Rotation = startRotation; rigidbodyComponent.Interpolate(endPosition, endRotation); }
void UpdateRunning() { //Calculate directional stiffness force //Vector3 velDir = transform.InverseTransformVector(rBody.velocity); //velDir = new Vector3(velDir.x, 0, 0); //Vector3 dirForce = -velDir * DirectionStiffness; //Get player velocity, calculate rate of acceleration float moveSpeed = IsCrouching ? Running.MaxCrouchSpeed : Running.MaxRunSpeed; Vector3 playerVelMs = playerObjectVelocity; playerVelMs.y = 0; float playerVelMag = playerVelMs.x * playerVelMs.x + playerVelMs.z * playerVelMs.z; RunSpeedPercent = Mathf.Pow(Mathf.Clamp01(playerVelMag / (moveSpeed * moveSpeed)), Running.AccelerationCurve); float velAccelMult = 1 - RunSpeedPercent; RawSpeed = Mathf.Sqrt(playerVelMag); IsRunning = isTryingToMove && RunSpeedPercent > 0.01f; inputAccelMult = Mathf.Clamp01(1 - (Vector3.Dot(horizontalPlaneVelocity.normalized, worldInputDirection) + 1) * 0.5f); //Calculate direction vectors Vector3 fwd = cameraTransform.rotation * Vector3.forward; fwd.y = 0; fwd = fwd.normalized; fwd = (Vector3.ProjectOnPlane(fwd, Hit.normal) + fwd).normalized; Vector3 right = cameraTransform.rotation * Vector3.right; right.y = 0; right = right.normalized; right = (Vector3.ProjectOnPlane(right, Hit.normal) + right).normalized; //Final steps & force application float accelMult = Mathf.Max(inputAccelMult, velAccelMult); float finalAccel = (IsGrounded ? (IsCrouching ? Running.CrouchAcceleration : Running.StandAcceleration) : Running.AirAcceleration) * accelMult; Vector3 finalForce = Vector3.zero; if (isTryingToMove) { finalForce = (inputs.x * finalAccel * right) + (inputs.y * finalAccel * fwd); } else if (IsGrounded && jumpTimer < Jumping.JumpResetTime * 0.5f) { finalForce = stopForce; } RigidbodyComponent.AddForce(finalForce /*+ dirForce*/, ForceMode.Acceleration); }
protected virtual void Awake() { if( GetComponent<Collider2D>() != null || GetComponent<Rigidbody2D>() != null) { rigidbodyComponent = gameObject.AddComponent<RigidbodyComponent2D>(); } else if( GetComponent<Collider>() != null || GetComponent<Rigidbody>() != null) { rigidbodyComponent = gameObject.AddComponent<RigidbodyComponent3D>(); } rigidbodyComponent.IsKinematic = true; rigidbodyComponent.UseInterpolation = true; }
/// <summary> /// Prevents jittering (as a result of applying joint limits) of bone and smoothly translate rigid from animated mode to ragdoll /// </summary> /// <param name="rigid"></param> /// <returns></returns> private static IEnumerator FixTransformAndEnableJoint(RigidbodyComponent joint) { if (joint.GetJoint() == null || !joint.GetJoint().autoConfigureConnectedAnchor) { yield break; } SoftJointLimit highTwistLimit = new SoftJointLimit(); SoftJointLimit lowTwistLimit = new SoftJointLimit(); SoftJointLimit swing1Limit = new SoftJointLimit(); SoftJointLimit swing2Limit = new SoftJointLimit(); SoftJointLimit curHighTwistLimit = highTwistLimit = joint.GetJoint().highTwistLimit; SoftJointLimit curLowTwistLimit = lowTwistLimit = joint.GetJoint().lowTwistLimit; SoftJointLimit curSwing1Limit = swing1Limit = joint.GetJoint().swing1Limit; SoftJointLimit curSwing2Limit = swing2Limit = joint.GetJoint().swing2Limit; float aTime = 0.3f; Vector3 startConPosition = joint.GetJoint().connectedBody.transform.InverseTransformVector(joint.GetJoint().transform.position - joint.GetJoint().connectedBody.transform.position); joint.GetJoint().autoConfigureConnectedAnchor = false; for (float t = 0.0f; t < 1.0f; t += Time.deltaTime / aTime) { Vector3 newConPosition = Vector3.Lerp(startConPosition, joint.GetConnectedAnchorDefault(), t); joint.GetJoint().connectedAnchor = newConPosition; curHighTwistLimit.limit = Mathf.Lerp(177, highTwistLimit.limit, t); curLowTwistLimit.limit = Mathf.Lerp(-177, lowTwistLimit.limit, t); curSwing1Limit.limit = Mathf.Lerp(177, swing1Limit.limit, t); curSwing2Limit.limit = Mathf.Lerp(177, swing2Limit.limit, t); joint.GetJoint().highTwistLimit = curHighTwistLimit; joint.GetJoint().lowTwistLimit = curLowTwistLimit; joint.GetJoint().swing1Limit = curSwing1Limit; joint.GetJoint().swing2Limit = curSwing2Limit; yield return(null); } joint.GetJoint().connectedAnchor = joint.GetConnectedAnchorDefault(); yield return(new WaitForFixedUpdate()); joint.GetJoint().autoConfigureConnectedAnchor = true; joint.GetJoint().highTwistLimit = highTwistLimit; joint.GetJoint().lowTwistLimit = lowTwistLimit; joint.GetJoint().swing1Limit = swing1Limit; joint.GetJoint().swing2Limit = swing2Limit; }
/// <inheritdoc/> public Constraint Build(RigidbodyComponent bodyA, RigidbodyComponent bodyB) { var frameA = Matrix.RotationQuaternion(AxisInA) * Matrix.Translation(PivotInA); var frameB = Matrix.RotationQuaternion(AxisInB) * Matrix.Translation(PivotInB); var coneTwist = (bodyB == null ? Simulation.CreateConstraint(ConstraintTypes.ConeTwist, bodyA, frameA) : Simulation.CreateConstraint(ConstraintTypes.ConeTwist, bodyA, bodyB, frameA, frameB) ) as ConeTwistConstraint; if (Limit.SetLimit) { coneTwist.SetLimit(Limit.SwingSpanY, Limit.SwingSpanZ, Limit.TwistSpan); } return(coneTwist); }
/// <inheritdoc/> public Constraint Build(RigidbodyComponent bodyA, RigidbodyComponent bodyB) { var frameA = Matrix.RotationQuaternion(AxisInA) * Matrix.Translation(PivotInA); var frameB = Matrix.RotationQuaternion(AxisInB) * Matrix.Translation(PivotInB); var slider = (bodyB == null ? Simulation.CreateConstraint(ConstraintTypes.Slider, bodyA, frameA, UseLinearReferenceFrameA) : Simulation.CreateConstraint(ConstraintTypes.Slider, bodyA, bodyB, frameA, frameB, UseLinearReferenceFrameA) ) as SliderConstraint; slider.LowerLinearLimit = Limit.LowerLinearLimit; slider.UpperLinearLimit = Limit.UpperLinearLimit; slider.LowerAngularLimit = Limit.LowerAngularLimit; slider.UpperAngularLimit = Limit.UpperAngularLimit; return(slider); }
static private Generic6DoFConstraint CreateWheelConstraint(RigidbodyComponent parent, RigidbodyComponent wheel) { Matrix wheelTranslation = Matrix.Translation(wheel.Entity.Transform.Position); Quaternion wheelRotation = wheel.Entity.Transform.Rotation; Generic6DoFConstraint wheelConstraint = Simulation.CreateConstraint( ConstraintTypes.Generic6DoF, parent, wheel, wheelTranslation, /* the constraint itself should be created at the offset where the wheel itself is */ Matrix.RotationQuaternion(wheelRotation), useReferenceFrameA: true ) as Generic6DoFConstraint; /* lock X and Y rotation */ wheelConstraint.AngularLowerLimit = new Vector3(0.0f, 0.0f, -(float)Math.PI); wheelConstraint.AngularUpperLimit = new Vector3(0.0f, 0.0f, (float)Math.PI); return(wheelConstraint); }
protected virtual void Awake() { Rigidbody2D rigidbody2D = GetComponent <Rigidbody2D>(); Rigidbody rigidbody3D = GetComponent <Rigidbody>(); if (rigidbody3D != null) { RigidbodyComponent = gameObject.GetOrAddComponent <RigidbodyComponent3D>(); } if (RigidbodyComponent == null) { this.enabled = false; } }
void UpdateLegSpring() { float legHeight = IsCrouching ? _legSpring.LegCrouchHeight : _legSpring.LegStandHeight; float springForce = 0; if (IsRolling) { springForce = -Mathf.Clamp01(Hit.distance / _legSpring.GroundedDistance + _legSpring.LegOffset + _legSpring.LegRadius); } else if (Hit.distance < _legSpring.LegOffset + legHeight - _legSpring.LegRadius) { float lerp = 1 - Mathf.Clamp01(Hit.distance / (_legSpring.LegOffset + legHeight - _legSpring.LegRadius)); springForce = Mathf.Lerp(1, _legSpring.LegStiffness, lerp); } else if (jumpTimer <= 0) { float lerp = 1 - Mathf.Clamp01((Hit.distance - _legSpring.LegOffset) / (_legSpring.GroundedDistance + _legSpring.LegRadius - _legSpring.LegOffset + legHeight)); float force = Mathf.Lerp(1, -1, lerp); springForce = force; } float curLegDist = Mathf.Clamp01(Hit.distance / (legHeight + _legSpring.LegOffset + _legSpring.GroundedDistance)); float springMult = 1 - curLegDist; float legVel = (prevLegDist - curLegDist) / Time.fixedDeltaTime; prevLegDist = curLegDist; float dampAdjust = 1 - Mathf.Clamp01((Hit.distance / (_legSpring.LegOffset + legHeight - _legSpring.LegRadius)) - 1); float legDamp = Mathf.Min(legVel * _legSpring.LegDamping, Hit.distance > (_legSpring.LegOffset + legHeight - _legSpring.LegRadius) ? 0 : Mathf.Infinity); legDamp = legVel * _legSpring.LegDamping * dampAdjust; float legForce = Mathf.Clamp(springForce + legDamp, jumpTimer > 0 ? 0 : _legSpring.LegMinForce, IsRolling ? 0 : _legSpring.LegMaxForce);//Mathf.Clamp(legStiffness * (springMult + legDamp), legMinForce, legMaxForce); if (hasValidHit) { RigidbodyComponent.AddForce(Vector3.up * -Physics.gravity.y * legForce, ForceMode.Acceleration); } float hitHeight = (Hit.distance + _legSpring.LegRadius) - _legSpring.LegOffset;//transform.InverseTransformPoint(rHit.point).y; CrouchAmount = Mathf.InverseLerp(_legSpring.LegStandHeight, _legSpring.LegCrouchHeight, hitHeight); //Debug.DrawRay(transform.position + -transform.forward * 0.1f, Vector3.up * legDamp, Color.green, 0, false); }