/// <summary> /// Called once per frame to ensure all rigid bodie components are activated /// </summary> void Update() { BRigidBody rigidBody = GetComponentInChildren <BRigidBody>(); if (!rigidBody.GetCollisionObject().IsActive) { rigidBody.GetCollisionObject().Activate(); } if (!IsResetting) { if (InputControl.GetButtonDown(Controls.buttons[controlIndex].resetRobot)) { keyDownTime = Time.time; } else if (InputControl.GetButton(Controls.buttons[controlIndex].resetRobot)) { if (Time.time - keyDownTime > HOLD_TIME) { IsResetting = true; BeginReset(); } } else if (InputControl.GetButtonUp(Controls.buttons[controlIndex].resetRobot)) { BeginReset(); EndReset(); } } }
/// <summary> /// Initializes the BRaycastVehicle. /// </summary> private void Awake() { rigidBody = GetComponent <BRigidBody>(); if (rigidBody == null) { Destroy(this); return; } RaycastRobot = new RaycastRobot(defaultVehicleTuning = new VehicleTuning { MaxSuspensionForce = 1000f, MaxSuspensionTravelCm = SuspensionToleranceCm, SuspensionDamping = 10f, SuspensionCompression = SuspensionCompressionRatio, SuspensionStiffness = CalculateStiffness(DefaultNumWheels), FrictionSlip = 2f }, (RigidBody)rigidBody.GetCollisionObject(), new BRobotRaycaster((DynamicsWorld)BPhysicsWorld.Get().world)); RaycastRobot.SetCoordinateSystem(0, 1, 2); BRobotManager.Instance.RegisterRaycastRobot(RaycastRobot); }
internal override void Start() { base.Start(); graphControl = FindObjectOfType <GraphController>(); go = this.gameObject; goBGhost = go.GetComponent <BGhostObject>(); goCo = goBGhost.GetCollisionObject(); goGhost = (GhostObject)goCo; goParent = go.transform.parent.gameObject; goParentRb = goParent.GetComponent <BRigidBody>(); goParentCo = goParentRb.GetCollisionObject(); if (goCo.CollisionShape is SphereShape) { sphRadius = this.gameObject.GetComponent <BSphereShape>().Radius; // when using a Sphere as CollisionObject } else if (goCo.CollisionShape is BoxShape) { sphRadius = this.gameObject.GetComponent <BBoxShape>().Extents.x; // when using a Box as CollisionObject. Box is assumed to have equal sides. } else { Debug.LogError("GhostObjPiggyBack2: CollisionObject not Sphere or Box. sphRadius will be empty, repulse not working."); } sphRadiusSqr = sphRadius * sphRadius; }
public void NewGoal() { int goalIndex = color.Equals("Red") ? redGoals[gamepieceIndex].Count() : blueGoals[gamepieceIndex].Count(); GameObject gameobject = new GameObject("Gamepiece" + gamepieceIndex.ToString() + "Goal" + goalIndex.ToString()); BBoxShape collider = gameobject.AddComponent <BBoxShape>(); BRigidBody rigid = gameobject.AddComponent <BRigidBody>(); rigid.collisionFlags = rigid.collisionFlags | BulletSharp.CollisionFlags.NoContactResponse | BulletSharp.CollisionFlags.StaticObject; Goal goal = gameobject.AddComponent <Goal>(); collider.Extents = new UnityEngine.Vector3(0.5f, 0.5f, 0.5f); rigid.SetPosition(new UnityEngine.Vector3(0, 4, 0)); goal.position = new UnityEngine.Vector3(0, 4, 0); goal.scale = Vector3.one; goal.SetKeyword(FieldDataHandler.gamepieces[gamepieceIndex].name); goal.description = "New Goal"; goal.color = color; if (color.Equals("Red")) { redGoals[gamepieceIndex].Add(gameobject); } else { blueGoals[gamepieceIndex].Add(gameobject); } InitializeDisplay(); WriteGoals(); }
/// <summary> /// Finds the nearest RigidBody that doesn't belong to the robot. /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="result"></param> /// <returns></returns> public object CastRay(ref Vector3 from, ref Vector3 to, VehicleRaycasterResult result) { AllHitsRayResultCallback rayCallback = new AllHitsRayResultCallback(from, to); dynamicsWorld.RayTest(from, to, rayCallback); int i = 0; foreach (CollisionObject co in rayCallback.CollisionObjects) { BRigidBody brb = co.UserObject as BRigidBody; if (brb != null) { if (!brb.gameObject.name.StartsWith("node_")) { result.HitPointInWorld = rayCallback.HitPointWorld[i]; result.HitNormalInWorld = rayCallback.HitNormalWorld[i]; result.HitNormalInWorld.Normalize(); result.DistFraction = rayCallback.HitFractions[i]; return(RigidBody.Upcast(co)); } } i++; } return(null); }
public void ApplyForce() { Ray ray = UnityEngine.Camera.main.ScreenPointToRay(UnityEngine.Input.mousePosition); float impulse; float.TryParse(GameObject.Find("ImpulseInputField").GetComponent <InputField>().text, out impulse); Vector3 a = ray.origin + (ray.direction * 1000); BulletSharp.Math.Vector3 from = new BulletSharp.Math.Vector3(ray.origin.x, ray.origin.y, ray.origin.z), to = new BulletSharp.Math.Vector3(a.x, a.y, a.z); ClosestRayResultCallback callback = new ClosestRayResultCallback(ref from, ref to); BPhysicsWorld world = BPhysicsWorld.Get(); world.world.RayTest(from, to, callback); BulletSharp.Math.Vector3 point = callback.HitNormalWorld; BRigidBody part = (BRigidBody)callback.CollisionObject.UserObject; foreach (BRigidBody br in GameObject.Find("Robot").GetComponentsInChildren <BRigidBody>()) { if (part == br) { Vector3 closestPoint = br.GetComponent <MeshRenderer>().bounds.ClosestPoint(point.ToUnity()); Ray normalRay = new Ray(point.ToUnity(), closestPoint - point.ToUnity()); part.AddImpulseAtPosition(ray.direction.normalized * impulse, point.ToUnity()); // part.AddImpulseAtPosition(normalRay.direction.normalized * impulse, normalRay.origin); } } }
/// <summary> /// Updates pwm information and sends robot information to the server. /// </summary> private void FixedUpdate() { base.UpdatePhysics(); BRigidBody rigidBody = GetComponentInChildren <BRigidBody>(); if (rigidBody == null) { return; } if (isLocalPlayer) { float[] pwm = DriveJoints.GetPwmValues(Packet == null ? emptyDIO : Packet.dio, ControlIndex, false); if (isServer) { RpcUpdateRobotInfo(pwm); } else { CmdUpdateRobotInfo(pwm); } if (InputControl.GetButton(Controls.buttons[ControlIndex].resetRobot)) { CmdResetRobot(); } } if (isServer && serverCanSendUpdate) { RemoteUpdateTransforms(); } }
/// <summary> /// Updates pwm information and sends robot information to the server. /// </summary> private void FixedUpdate() { base.UpdatePhysics(); BRigidBody rigidBody = GetComponentInChildren <BRigidBody>(); if (rigidBody == null) { return; } if (isLocalPlayer) { float[] pwm = DriveJoints.GetPwmValues(Packet == null ? emptyDIO : Packet.dio, ControlIndex, false); if (correctionEnabled) { if (isServer) { RpcUpdateRobotInfo(pwm); } else { CmdUpdateRobotInfo(pwm); } } } if (isServer && serverCanSendUpdate && correctionEnabled) { RemoteUpdateTransforms(); } }
private void UpdateWheelMass() { BRigidBody rigidBody = MainObject.GetComponent <BRigidBody>(); rigidBody.mass *= WHEEL_MASS_SCALE; rigidBody.GetCollisionObject().CollisionShape.CalculateLocalInertia(rigidBody.mass); }
/// <summary> /// Builds the constraint. /// </summary> /// <returns></returns> internal override bool _BuildConstraint() { BPhysicsWorld world = BPhysicsWorld.Get(); if (m_constraintPtr != null) { if (m_isInWorld && world != null) { m_isInWorld = false; world.RemoveConstraint(m_constraintPtr); } } BRigidBody targetRigidBodyA = GetComponent <BRigidBody>(); if (targetRigidBodyA == null) { Debug.LogError("BallSocketConstraint needs to be added to a component with a BRigidBody."); return(false); } if (!targetRigidBodyA.isInWorld) { world.AddRigidBody(targetRigidBodyA); } RigidBody rba = (RigidBody)targetRigidBodyA.GetCollisionObject(); if (rba == null) { Debug.LogError("Constraint could not get bullet RigidBody from target rigid body A"); return(false); } if (m_constraintType == ConstraintType.constrainToAnotherBody) { if (m_otherRigidBody == null) { Debug.LogError("Other rigid body was not set"); return(false); } if (!m_otherRigidBody.isInWorld) { world.AddRigidBody(m_otherRigidBody); } RigidBody rbb = (RigidBody)m_otherRigidBody.GetCollisionObject(); if (rbb == null) { Debug.LogError("Constraint could not get bullet RigidBody from target rigid body B"); return(false); } Vector3 pivotInOther = m_otherRigidBody.transform.InverseTransformPoint(targetRigidBodyA.transform.TransformPoint(m_localConstraintPoint)); m_constraintPtr = new Point2PointConstraint(rbb, rba, pivotInOther.ToBullet(), m_localConstraintPoint.ToBullet()); } else { m_constraintPtr = new Point2PointConstraint(rba, _pivotInA); } m_constraintPtr.Userobject = this; m_constraintPtr.BreakingImpulseThreshold = m_breakingImpulseThreshold; m_constraintPtr.DebugDrawSize = m_debugDrawSize; m_constraintPtr.OverrideNumSolverIterations = m_overrideNumSolverIterations; return(true); }
/// <summary> /// Gets blue goals as list of list of Goal objects from field_data.xml /// </summary> private static List <List <GameObject> > getBlueGoals() { List <List <GameObject> > goals = new List <List <GameObject> >(); foreach (XElement z in file.Root.Element("Goals").Element("BlueGoals").Elements()) { List <GameObject> temp = new List <GameObject>(); foreach (XElement e in z.Elements()) { GameObject g = new GameObject("Gamepiece" + goals.Count().ToString() + "Goal" + temp.Count().ToString()); BBoxShape collider = g.AddComponent <BBoxShape>(); BRigidBody rigid = g.AddComponent <BRigidBody>(); rigid.collisionFlags = rigid.collisionFlags | BulletSharp.CollisionFlags.NoContactResponse | BulletSharp.CollisionFlags.StaticObject; Goal goal = g.AddComponent <Goal>(); collider.Extents = new UnityEngine.Vector3(0.5f, 0.5f, 0.5f); goal.pointValue = int.Parse(e.Element("Points").Value); goal.position = new UnityEngine.Vector3(float.Parse(e.Element("Position").Attribute("x").Value), float.Parse(e.Element("Position").Attribute("y").Value), float.Parse(e.Element("Position").Attribute("z").Value)); rigid.SetPosition(goal.position); goal.scale = new UnityEngine.Vector3(float.Parse(e.Element("Scale").Attribute("x").Value), float.Parse(e.Element("Scale").Attribute("y").Value), float.Parse(e.Element("Scale").Attribute("z").Value)); collider.LocalScaling = goal.scale; goal.gamepieceKeyword = e.Element("Keyword").Value; goal.description = e.Element("Description").Value; goal.color = e.Attribute("Color").Value; temp.Add(g); } goals.Add(temp); } //increases depth of list to number of gamepieces for future goal writing while (goals.Count != gamepieces.Count) { goals.Add(new List <GameObject>()); } return(goals); }
public bool AddRigidBody(BRigidBody rb) { if (!isDisposed) { if (physicWorldParameters.worldType < WorldType.RigidBodyDynamics) { Debug.LogError("World type must not be collision only"); return(false); } if (physicWorldParameters.debugType >= BDebug.DebugType.Debug) { Debug.LogFormat("Adding rigidbody {0} to world", rb); } if (rb._BuildCollisionObject()) { DWorld.AddRigidBody((RigidBody)rb.GetCollisionObject(), rb.groupsIBelongTo, rb.collisionMask); rb.isInWorld = true; } return(true); } return(false); }
/// <summary> /// Rotates the robot about its origin by a mathematical 4x4 matrix /// </summary> public void RotateRobot(BulletSharp.Math.Matrix rotationMatrix) { BulletSharp.Math.Vector3?origin = null; foreach (RigidNode n in RootNode.ListAllNodes()) { BRigidBody br = n.MainObject.GetComponent <BRigidBody>(); if (br == null) { continue; } RigidBody r = (RigidBody)br.GetCollisionObject(); if (origin == null) { origin = r.CenterOfMassPosition; } BulletSharp.Math.Matrix rotationTransform = new BulletSharp.Math.Matrix { Basis = rotationMatrix, Origin = BulletSharp.Math.Vector3.Zero }; BulletSharp.Math.Matrix currentTransform = r.WorldTransform; BulletSharp.Math.Vector3 pos = currentTransform.Origin; currentTransform.Origin -= origin.Value; currentTransform *= rotationTransform; currentTransform.Origin += origin.Value; r.WorldTransform = currentTransform; } }
private void HoldGamepiece(int id) { while (objectsHeld.Count <= id) { objectsHeld.Add(new List <GameObject>()); } if (objectsHeld[id].Count == 0) { return; } foreach (GameObject g in objectsHeld[id]) { BRigidBody orb = g.GetComponent <BRigidBody>(); if (UnityEngine.Input.GetKey(KeyCode.Backslash)) { ((RigidBody)orb.GetCollisionObject()).ClearForces(); } UnityEngine.Vector3 releasePosition = DPMDataHandler.dpmodes.Where(d => d.gamepiece.Equals(FieldDataHandler.gamepieces[id].name)).ToArray()[0].releasePosition; if (orb.GetComponent <BFixedConstraintEx>().localConstraintPoint != releasePosition) { orb.GetCollisionObject().Activate(); orb.GetComponent <BFixedConstraintEx>().localConstraintPoint = releasePosition; } } }
/// <summary> /// When called, the <see cref="NetworkElement"/>'s ability to send transform /// updates is re-enabled. /// </summary> private void Update() { if (networkMesh == null) { networkMesh = GetComponent <NetworkMesh>(); } if (UnityEngine.Input.GetKey(KeyCode.E)) { correctionEnabled = true; } else if (UnityEngine.Input.GetKey(KeyCode.D)) { correctionEnabled = false; } canSendUpdate = true; if (rigidBody == null) { BRigidBody bRigidBody = gameObject.GetComponent <BRigidBody>(); if (bRigidBody != null) { rigidBody = (RigidBody)bRigidBody.GetCollisionObject(); } } }
/// <summary> /// Return the robot to robotStartPosition and destroy extra game pieces /// </summary> /// <param name="resetTransform"></param> public void BeginReset() { IsResetting = true; foreach (RigidNode n in rootNode.ListAllNodes()) { BRigidBody br = n.MainObject.GetComponent <BRigidBody>(); if (br == null) { continue; } RigidBody r = (RigidBody)br.GetCollisionObject(); r.LinearVelocity = r.AngularVelocity = BulletSharp.Math.Vector3.Zero; r.LinearFactor = r.AngularFactor = BulletSharp.Math.Vector3.Zero; BulletSharp.Math.Matrix newTransform = r.WorldTransform; newTransform.Origin = (robotStartPosition + n.ComOffset).ToBullet(); newTransform.Basis = BulletSharp.Math.Matrix.Identity; r.WorldTransform = newTransform; } int isMixAndMatch = PlayerPrefs.GetInt("mixAndMatch"); // 0 is false, 1 is true if (robotHasManipulator == 1 && isMixAndMatch == 1) { foreach (RigidNode n in manipulatorNode.ListAllNodes()) { BRigidBody br = n.MainObject.GetComponent <BRigidBody>(); if (br == null) { continue; } RigidBody r = (RigidBody)br.GetCollisionObject(); r.LinearVelocity = r.AngularVelocity = BulletSharp.Math.Vector3.Zero; r.LinearFactor = r.AngularFactor = BulletSharp.Math.Vector3.Zero; BulletSharp.Math.Matrix newTransform = r.WorldTransform; newTransform.Origin = (robotStartPosition + n.ComOffset).ToBullet(); newTransform.Basis = BulletSharp.Math.Matrix.Identity; r.WorldTransform = newTransform; } } //Where "save orientation" works RotateRobot(robotStartOrientation); GameObject.Find("Robot").transform.GetChild(0).transform.position = new Vector3(10, 20, 5); if (IsResetting) { Debug.Log("is resetting!"); } }
private void UpdateWheelRigidBody(float friction) { BRigidBody rigidBody = MainObject.GetComponent <BRigidBody>(); rigidBody.friction = friction; rigidBody.GetCollisionObject().CcdMotionThreshold = CCD_MOTION_THRESHOLD; rigidBody.GetCollisionObject().CcdSweptSphereRadius = CCD_SWEPT_SPHERE_RADIUS; }
void Start() { rigidBody = GetComponent <BRigidBody>(); if (rigidBody == null) { rigidBody = GetComponentInParent <BRigidBody>(); } }
public override void BOnCollisionEnter(CollisionObject otherObj, BCollisionCallbacksDefault.PersistentManifoldList mList) { BRigidBody obj = (BRigidBody)otherObj.UserObject; GameObject g = obj.gameObject; sza.CollisionHandler(g); Debug.Log("Got collision with " + g); // We don't do anything if we neither destroy or reinstantiate }
void FixedUpdate() { if (Input.GetKey(KeyCode.M)) { SceneManager.LoadScene("MainMenu"); } if (rootNode != null) { UnityPacket.OutputStatePacket packet = unityPacket.GetLastPacket(); DriveJoints.UpdateAllMotors(rootNode, packet.dio); } BRigidBody rigidBody = robotObject.GetComponentInChildren <BRigidBody>(); if (Input.GetKey(KeyCode.R)) { if (!resetting) { foreach (GameObject g in extraElements) { Destroy(g); } BeginReset(); resetting = true; } Vector3 transposition = new Vector3( Input.GetKey(KeyCode.RightArrow) ? RESET_VELOCITY : Input.GetKey(KeyCode.LeftArrow) ? -RESET_VELOCITY : 0f, 0f, Input.GetKey(KeyCode.UpArrow) ? RESET_VELOCITY : Input.GetKey(KeyCode.DownArrow) ? -RESET_VELOCITY : 0f); if (!transposition.Equals(Vector3.zero)) { TransposeRobot(transposition); } } else { EndReset(); resetting = false; } if (!rigidBody.GetCollisionObject().IsActive) { rigidBody.GetCollisionObject().Activate(); } }
/// <summary> /// Releases the gamepiece from the robot at a set velocity /// </summary> private void ReleaseGamepiece(int index) { if (objectsHeld[index].Count > 0) { BRigidBody orb = objectsHeld[index][0].GetComponent <BRigidBody>(); orb.collisionFlags = BulletSharp.CollisionFlags.None; orb.velocity += releaseNode[index].transform.rotation * releaseVelocityVector[index]; orb.angularFactor = UnityEngine.Vector3.one; StartCoroutine(UnIgnoreCollision(objectsHeld[index][0])); intakeInteractor[index].heldGamepieces.Remove(objectsHeld[index][0]); objectsHeld[index].RemoveAt(0); } }
/// <summary> /// Updates positional information of the robot. /// </summary> protected virtual void UpdateTransform() { BRigidBody rigidBody = GetComponentInChildren <BRigidBody>(); if (rigidBody == null) { AppModel.ErrorToMenu("Could not generate robot physics data."); } else if (!rigidBody.GetCollisionObject().IsActive) { rigidBody.GetCollisionObject().Activate(); } }
/// <summary> /// Ensures that the robot is awake and enables sending the next packet to the server. /// </summary> protected override void UpdateTransform() { base.UpdateTransform(); BRigidBody rigidBody = GetComponentInChildren <BRigidBody>(); if (rigidBody == null) { return; } serverCanSendUpdate = true; }
/// <summary> /// Finds any robot collisions and adds them to the list of contact points. /// </summary> /// <param name="pm"></param> public void OnVisitPersistentManifold(PersistentManifold pm) { if (!mainState.Tracking) { return; } if (framesPassed == -1) { framesPassed = physicsWorld.frameCount - lastFrameCount; for (int i = 0; i < framesPassed; i++) { ContactPoints.Add(new List <ContactDescriptor>()); } } BRigidBody obA = pm.Body0.UserObject as BRigidBody; BRigidBody obB = pm.Body1.UserObject as BRigidBody; BRigidBody robotBody = obA != null && obA.gameObject.name.StartsWith("node") ? obA : obB != null && obB.gameObject.name.StartsWith("node") ? obB : null; if (robotBody == null) { return; } if (pm.NumContacts < 1) { return; } int numContacts = pm.NumContacts; for (int i = 0; i < Math.Min(framesPassed, numContacts); i++) { ManifoldPoint mp = pm.GetContactPoint(i); ContactDescriptor cd = new ContactDescriptor { AppliedImpulse = mp.AppliedImpulse, Position = (mp.PositionWorldOnA + mp.PositionWorldOnB) * 0.5f, RobotBody = robotBody }; if (ContactPoints[i] != null) { ContactPoints[i].Add(cd); } } }
/// <summary> /// Unlocks the robot's movement. /// </summary> protected void EndRobotReset() { foreach (RigidNode n in RootNode.ListAllNodes()) { BRigidBody br = n.MainObject.GetComponent <BRigidBody>(); if (br == null) { continue; } RigidBody r = (RigidBody)br.GetCollisionObject(); r.LinearFactor = r.AngularFactor = BulletSharp.Math.Vector3.One; } }
/// <summary> /// Gets goals as list of list of Goal objects from field_data.xml, picking color from argument /// </summary> private static List <List <GameObject> > getGoals(string goalsName) { List <List <GameObject> > goals = new List <List <GameObject> >(); foreach (XElement z in file.Root.Element("Goals").Element(goalsName).Elements()) { List <GameObject> temp = new List <GameObject>(); foreach (XElement e in z.Elements()) { GameObject g = new GameObject("Gamepiece" + goals.Count().ToString() + "Goal" + temp.Count().ToString()); g.transform.SetParent(GoalManager.GoalParent.transform); BBoxShape collider = g.AddComponent <BBoxShape>(); BRigidBody rigid = g.AddComponent <BRigidBody>(); rigid.collisionFlags = rigid.collisionFlags | BulletSharp.CollisionFlags.NoContactResponse | BulletSharp.CollisionFlags.StaticObject; Goal goal = g.AddComponent <Goal>(); collider.Extents = new UnityEngine.Vector3(0.5f, 0.5f, 0.5f); goal.pointValue = int.Parse(e.Element("Points").Value); goal.SetKeepScored(bool.Parse(e.Element("KeepScored").Value)); goal.position = new UnityEngine.Vector3(float.Parse(e.Element("Position").Attribute("x").Value), float.Parse(e.Element("Position").Attribute("y").Value), float.Parse(e.Element("Position").Attribute("z").Value)); rigid.SetPosition(goal.position); try { goal.rotation = new UnityEngine.Vector3(float.Parse(e.Element("Position").Attribute("i").Value), float.Parse(e.Element("Position").Attribute("j").Value), float.Parse(e.Element("Position").Attribute("k").Value)); } catch (System.Exception) { goal.rotation = Vector3.zero; } rigid.SetRotation(Quaternion.Euler(goal.rotation)); goal.scale = new UnityEngine.Vector3(float.Parse(e.Element("Scale").Attribute("x").Value), float.Parse(e.Element("Scale").Attribute("y").Value), float.Parse(e.Element("Scale").Attribute("z").Value)); collider.LocalScaling = goal.scale; goal.gamepieceKeyword = e.Element("Keyword").Value; goal.description = e.Element("Description").Value; goal.color = e.Attribute("Color").Value; try { goal.Sticky = bool.Parse(e.Element("Sticky").Value); } catch (Exception excep) { goal.Sticky = false; } temp.Add(g); } goals.Add(temp); } //increases depth of list to number of gamepieces for future goal writing while (goals.Count != gamepieces.Count) { goals.Add(new List <GameObject>()); } return(goals); }
/// <summary> /// Locks the robot in place. /// </summary> public void LockRobot() { foreach (RigidNode n in RootNode.ListAllNodes()) { BRigidBody br = n.MainObject.GetComponent <BRigidBody>(); if (br == null) { continue; } RigidBody r = (RigidBody)br.GetCollisionObject(); r.LinearVelocity = r.AngularVelocity = BulletSharp.Math.Vector3.Zero; r.LinearFactor = r.AngularFactor = BulletSharp.Math.Vector3.Zero; } }
/// <summary> /// Shifts the robot by a set position vector /// </summary> public void TransposeRobot(Vector3 transposition) { foreach (RigidNode n in rootNode.ListAllNodes()) { BRigidBody br = n.MainObject.GetComponent <BRigidBody>(); if (br == null) { continue; } RigidBody r = (RigidBody)br.GetCollisionObject(); BulletSharp.Math.Matrix newTransform = r.WorldTransform; newTransform.Origin += transposition.ToBullet(); r.WorldTransform = newTransform; } }
/// <summary> /// Updates constraint information for the active object, if applicable. /// </summary> private void Update() { if (Input.GetMouseButtonDown(0) && (Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt)) && constraint == null) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); BulletSharp.Math.Vector3 start = ray.origin.ToBullet(); BulletSharp.Math.Vector3 end = ray.GetPoint(100).ToBullet(); ClosestRayResultCallback callback = new ClosestRayResultCallback(ref start, ref end); BPhysicsWorld.Get().world.RayTest(start, end, callback); rayDistance = (start - callback.HitPointWorld).Length; if (callback.CollisionObject != null) { BRigidBody rigidBody = callback.CollisionObject.UserObject as BRigidBody; if (rigidBody != null && rigidBody.mass > 0f) { initialState = rigidBody.GetCollisionObject().ActivationState; rigidBody.GetCollisionObject().ActivationState = ActivationState.DisableDeactivation; initialDamping = rigidBody.angularDamping; rigidBody.angularDamping = 0.9f; constraint = rigidBody.gameObject.AddComponent <BBallSocketConstraintEx>(); constraint.PivotInA = rigidBody.transform.InverseTransformPoint(callback.HitPointWorld.ToUnity()).ToBullet(); constraint.constraintType = BTypedConstraint.ConstraintType.constrainToPointInSpace; } } } else if (Input.GetMouseButtonUp(0) && constraint != null) { constraint.thisRigidBody.GetCollisionObject().ActivationState = initialState; constraint.GetComponent <BRigidBody>().angularDamping = initialDamping; Destroy(constraint); constraint = null; } else if (constraint != null) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); constraint.PivotInB = ray.GetPoint(rayDistance).ToBullet(); } }
/// <summary> /// Updates positional information of the robot. /// </summary> protected override void UpdateTransform() { base.UpdateTransform(); // TODO: Utilize the state machine here if possible if (IsResetting) { BRigidBody rigidBody = GetComponentInChildren <BRigidBody>(); if (!rigidBody.GetCollisionObject().IsActive) { rigidBody.GetCollisionObject().Activate(); } Resetting(); } else if (InputControl.GetButtonDown(Controls.Players[ControlIndex].GetButtons().resetRobot)) { keyDownTime = Time.time; } else if (InputControl.GetButtonDown(Controls.Global.GetButtons().resetField)) { Auxiliary.FindObject(GameObject.Find("Canvas"), "LoadingPanel").SetActive(true); SceneManager.LoadScene("Scene"); AnalyticsManager.GlobalInstance.LogTimingAsync(AnalyticsLedger.TimingCatagory.MainSimulator, AnalyticsLedger.TimingVarible.Playing, AnalyticsLedger.TimingLabel.ChangeField); } else if (InputControl.GetButton(Controls.Players[ControlIndex].GetButtons().resetRobot) && !state.DynamicCameraObject.GetComponent <DynamicCamera>().ActiveState.GetType().Equals(typeof(DynamicCamera.ConfigurationState))) { if (Time.time - keyDownTime > HoldTime) { BeginReset(); } } else if (InputControl.GetButtonUp(Controls.Players[ControlIndex].GetButtons().resetRobot)) { BeginReset(); EndReset(); } }
//IMPORTANT Time.fixedTime must match the timestep being used here. public static List<UnityEngine.Vector3> SimulateBall(BRigidBody ballRb, UnityEngine.Vector3 ballThrowForce, int numberOfSimulationSteps, bool reverseOrder) { var ballPositions = new List<UnityEngine.Vector3>(numberOfSimulationSteps); //Create a World Debug.Log("Initialize physics"); CollisionConfiguration CollisionConf; CollisionDispatcher Dispatcher; BroadphaseInterface Broadphase; CollisionWorld cw; SequentialImpulseConstraintSolver Solver; BulletSharp.SoftBody.SoftBodyWorldInfo softBodyWorldInfo; //This should create a copy of the BPhysicsWorld with the same settings BPhysicsWorld bw = BPhysicsWorld.Get(); bw.CreatePhysicsWorld(out cw, out CollisionConf, out Dispatcher, out Broadphase, out Solver, out softBodyWorldInfo); World = (DiscreteDynamicsWorld) cw; //Copy all existing rigidbodies in scene // IMPORTANT rigidbodies must be added to the offline world in the same order that they are in the source world // this is because collisions must be resolved in the same order for the sim to be deterministic DiscreteDynamicsWorld sourceWorld = (DiscreteDynamicsWorld) bw.world; BulletSharp.RigidBody bulletBallRb = null; BulletSharp.Math.Matrix mm = BulletSharp.Math.Matrix.Identity; for(int i = 0; i < sourceWorld.NumCollisionObjects; i++) { CollisionObject co = sourceWorld.CollisionObjectArray[i]; if (co != null && co.UserObject is BRigidBody) { BRigidBody rb = (BRigidBody) co.UserObject; float mass = rb.isDynamic() ? rb.mass : 0f; BCollisionShape existingShape = rb.GetComponent<BCollisionShape>(); CollisionShape shape = null; if (existingShape is BSphereShape) { shape = ((BSphereShape)existingShape).CopyCollisionShape(); } else if (existingShape is BBoxShape) { shape = ((BBoxShape)existingShape).CopyCollisionShape(); } RigidBody bulletRB = null; BulletSharp.Math.Vector3 localInertia = new BulletSharp.Math.Vector3(); rb.CreateOrConfigureRigidBody(ref bulletRB, ref localInertia, shape, null); BulletSharp.Math.Vector3 pos = rb.GetCollisionObject().WorldTransform.Origin; BulletSharp.Math.Quaternion rot = rb.GetCollisionObject().WorldTransform.GetOrientation(); BulletSharp.Math.Matrix.AffineTransformation(1f, ref rot, ref pos, out mm); bulletRB.WorldTransform = mm; World.AddRigidBody(bulletRB, rb.groupsIBelongTo, rb.collisionMask); if (rb == ballRb) { bulletBallRb = bulletRB; bulletRB.ApplyCentralImpulse(ballThrowForce.ToBullet()); } } } //Step the simulation numberOfSimulationSteps times for (int i = 0; i < numberOfSimulationSteps; i++) { int numSteps = World.StepSimulation(1f / 60f, 10, 1f / 60f); ballPositions.Add(bulletBallRb.WorldTransform.Origin.ToUnity()); } UnityEngine.Debug.Log("ExitPhysics"); if (World != null) { //remove/dispose constraints int i; for (i = World.NumConstraints - 1; i >= 0; i--) { TypedConstraint constraint = World.GetConstraint(i); World.RemoveConstraint(constraint); constraint.Dispose(); } //remove the rigidbodies from the dynamics world and delete them for (i = World.NumCollisionObjects - 1; i >= 0; i--) { CollisionObject obj = World.CollisionObjectArray[i]; RigidBody body = obj as RigidBody; if (body != null && body.MotionState != null) { body.MotionState.Dispose(); } World.RemoveCollisionObject(obj); obj.Dispose(); } World.Dispose(); Broadphase.Dispose(); Dispatcher.Dispose(); CollisionConf.Dispose(); } if (Broadphase != null) { Broadphase.Dispose(); } if (Dispatcher != null) { Dispatcher.Dispose(); } if (CollisionConf != null) { CollisionConf.Dispose(); } return ballPositions; }
void OnEnable() { rb = (BRigidBody)target; }
void Start() { brb = GetComponent<BRigidBody>(); }
// Use this for initialization void Start() { rb = GetComponent<BRigidBody>(); rb.velocity = Vector3.right * 4f; rb.angularVelocity = Vector3.up * 5f; }