/// <summary> /// Set the node where the camera will be attached to /// </summary> public void SetNode() { //Casts a ray from the camera in the direction the mouse is in and returns the closest object hit Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); BulletSharp.Math.Vector3 start = ray.origin.ToBullet(); BulletSharp.Math.Vector3 end = ray.GetPoint(200).ToBullet(); //Creates a callback result that will be updated if we do a ray test with it ClosestRayResultCallback rayResult = new ClosestRayResultCallback(ref start, ref end); //Retrieves the bullet physics world and does a ray test with the given coordinates and updates the callback object BPhysicsWorld world = BPhysicsWorld.Get(); world.world.RayTest(start, end, rayResult); Debug.Log("Selected:" + rayResult.CollisionObject); //If there is a collision object and it is a robot part, set that to be new attachment point if (rayResult.CollisionObject != null) { GameObject selectedObject = ((BRigidBody)rayResult.CollisionObject.UserObject).gameObject; if (selectedObject.transform.parent != null && selectedObject.transform.parent.name == "Robot") { string name = selectedObject.name; SelectedNode = selectedObject; UserMessageManager.Dispatch(name + " has been selected as the node for camera attachment", 5); } else { UserMessageManager.Dispatch("Please select a robot node", 3); } } }
/// <summary> /// Allows the user to select a robot node with their mouse and change the intake/release node /// </summary> /// <param name="index">configuring index</param> public void SetMechanism(int index) { //Casts a ray from the camera in the direction the mouse is in and returns the closest object hit Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); BulletSharp.Math.Vector3 start = ray.origin.ToBullet(); BulletSharp.Math.Vector3 end = ray.GetPoint(200).ToBullet(); //Creates a callback result that will be updated if we do a ray test with it ClosestRayResultCallback rayResult = new ClosestRayResultCallback(ref start, ref end); //Retrieves the bullet physics world and does a ray test with the given coordinates and updates the callback object BPhysicsWorld world = BPhysicsWorld.Get(); world.world.RayTest(start, end, rayResult); //If there is a collision object and it is dynamic and not a robot part, change the gamepiece to that if (rayResult.CollisionObject != null) { GameObject collisionObject = (rayResult.CollisionObject.UserObject as BRigidBody).gameObject; if (rayResult.CollisionObject.CollisionFlags == BulletSharp.CollisionFlags.StaticObject) { UserMessageManager.Dispatch("Please click on a robot part", 3); } else if (collisionObject == null) { Debug.Log("DPM: Game object not found"); } else if (collisionObject.transform.parent == transform) { if (definingIntake) { intakeNode[index] = collisionObject; SetInteractor(intakeNode[index], index); UserMessageManager.Dispatch(collisionObject.name + " has been selected as intake node", 5); definingIntake = false; } else { releaseNode[index] = collisionObject; SetInteractor(releaseNode[index], index); UserMessageManager.Dispatch(collisionObject.name + " has been selected as release node", 5); definingRelease = false; } RevertNodeColors(hoveredNode, hoveredColors); } else { UserMessageManager.Dispatch("A gamepiece is NOT a robot part!", 3); } } else { } }
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); } } }
public void cast(CollisionWorld cw) { #if USE_BT_CLOCK frame_timer.reset(); #endif //USE_BT_CLOCK #if BATCH_RAYCASTER if (gBatchRaycaster == null) { return; } gBatchRaycaster.clearRays(); for (int i = 0; i < NUMRAYS_IN_BAR; i++) { gBatchRaycaster.addRay(source[i], dest[i]); } gBatchRaycaster.performBatchRaycast(); for (int i = 0; i < gBatchRaycaster.getNumRays(); i++) { const SpuRaycastTaskWorkUnitOut& outResult = (*gBatchRaycaster)[i]; hit[i].setInterpolate3(source[i], dest[i], outResult.hitFraction); normal[i] = outResult.hitNormal; normal[i] = normal[i].Normalize(); } #else for (int i = 0; i < NUMRAYS_IN_BAR; i++) { ClosestRayResultCallback cb = new ClosestRayResultCallback(source[i], dest[i]); cw.RayTest(ref source[i], ref dest[i], cb); if (cb.HasHit()) { hit[i] = cb.m_hitPointWorld; normal[i] = cb.m_hitNormalWorld; normal[i] = IndexedVector3.Normalize(normal[i]); } else { hit[i] = dest[i]; normal[i] = new IndexedVector3(1.0f, 0.0f, 0.0f); } } #if USE_BT_CLOCK ms += frame_timer.getTimeMilliseconds(); #endif //USE_BT_CLOCK frame_counter++; if (frame_counter > 50) { min_ms = ms < min_ms ? ms : min_ms; max_ms = ms > max_ms ? ms : max_ms; sum_ms += ms; sum_ms_samples++; float mean_ms = (float)sum_ms / (float)sum_ms_samples; //printf("%d rays in %d ms %d %d %f\n", NUMRAYS_IN_BAR * frame_counter, ms, min_ms, max_ms, mean_ms); ms = 0; frame_counter = 0; } #endif }
/// <summary> /// Shoot an invisable bullet to apply impulse to the rigidbody it hits. /// </summary> /// <param name="from">eye pos.</param> /// <param name="force">contains direction and intensity.</param> public static void Shoot(Vector3 *from, Vector3 *force) { var gunPos = *from * GBConstant.G2BScale; var to = gunPos + *force * GBConstant.G2BScale; var world = BWorld.Instance; using (var rayCallback = new ClosestRayResultCallback(ref gunPos, ref to)) { world.RayTestRef(ref *from, ref to, rayCallback); if (rayCallback.HasHit) { Vector3 pickPosition = rayCallback.HitPointWorld; var body = rayCallback.CollisionObject as RigidBody; if (body != null) { body.ApplyCentralImpulseRef(ref *force); } //else //{ // var collider = rayCallback.CollisionObject as MultiBodyLinkCollider; // if (collider != null) // { // (collider as RigidBody).ApplyCentralImpulseRef(ref *force); // } //} } } }
public static bool Raycast(Vector3 source, Vector3 destination, out RaycastHitInfo info) { if (_contextWorld == null) { Log.Core.Error("raycast attempted without world context!"); throw new InvalidOperationException("Raycast attempted without world context."); } BulletVector3 Bdestination = destination.ToBullet(); BulletVector3 Bsource = source.ToBullet(); using (var cb = new ClosestRayResultCallback(ref Bsource, ref Bdestination)) { _contextWorld.RayTestRef(ref Bsource, ref Bdestination, cb); if (cb.HasHit) { info = new RaycastHitInfo(cb.HitPointWorld.ToNumerics(), Vector3.Normalize(cb.HitNormalWorld.ToNumerics()), (RigidBodyComponent)cb.CollisionObject.UserObject, (ColliderComponent)cb.CollisionObject.CollisionShape.UserObject); return(true); } else { info = new RaycastHitInfo(destination, new Vector3(1.0f, 0.0f, 0.0f), null); return(false); } } }
private void PickBody() { Vector3 rayFrom = _demo.FreeLook.Eye; Vector3 rayTo = _demo.GetCameraRayTo(); DiscreteDynamicsWorld world = _demo.Simulation.World; using (var rayCallback = new ClosestRayResultCallback(ref rayFrom, ref rayTo)) { world.RayTestRef(ref rayFrom, ref rayTo, rayCallback); if (rayCallback.HasHit) { Vector3 pickPosition = rayCallback.HitPointWorld; var body = rayCallback.CollisionObject as RigidBody; if (body != null) { PickRigidBody(body, ref pickPosition); } else { var collider = rayCallback.CollisionObject as MultiBodyLinkCollider; if (collider != null) { PickMultiBody(collider, ref pickPosition); } } _oldPickingDist = (pickPosition - rayFrom).Length; } } }
public bool PointRaycast(PhysicsObject me, Vector3 origin, Vector3 direction, float maxDist, out Vector3 contactPoint, out PhysicsObject didHit) { contactPoint = Vector3.Zero; didHit = null; ClosestRayResultCallback cb; var from = origin.Cast(); var to = (origin + direction * maxDist).Cast(); if (me != null) { cb = new KinematicClosestNotMeRayResultCallback(me.RigidBody); cb.RayFromWorld = from; cb.RayToWorld = to; } else { cb = new ClosestRayResultCallback(ref from, ref to); } using (cb) { btWorld.RayTestRef(ref from, ref to, cb); if (cb.HasHit) { didHit = cb.CollisionObject.UserObject as PhysicsObject; contactPoint = cb.HitPointWorld.Cast(); return(true); } return(false); } }
public virtual Object CastRay(ref IndexedVector3 from, ref IndexedVector3 to, ref VehicleRaycasterResult result) { // RayResultCallback& resultCallback; ClosestRayResultCallback rayCallback = new ClosestRayResultCallback(ref from, ref to); m_dynamicsWorld.RayTest(ref from, ref to, rayCallback); if (rayCallback.HasHit()) { RigidBody body = RigidBody.Upcast(rayCallback.m_collisionObject); if (body != null && body.HasContactResponse()) { result.m_hitPointInWorld = rayCallback.m_hitPointWorld; result.m_hitNormalInWorld = rayCallback.m_hitNormalWorld; result.m_hitNormalInWorld.Normalize(); result.m_distFraction = rayCallback.m_closestHitFraction; return(body); } } else { int ibreak = 0; ClosestRayResultCallback rayCallback2 = new ClosestRayResultCallback(ref from, ref to); m_dynamicsWorld.RayTest(ref from, ref to, rayCallback2); } rayCallback.Cleanup(); return(null); }
/// <summary> /// When user click left mouse, use raycast to select a node for attachment, and highlight accordingly /// </summary> public void SetNode() { //Casts a ray from the camera in the direction the mouse is in and returns the closest object hit Ray ray = UnityEngine.Camera.main.ScreenPointToRay(UnityEngine.Input.mousePosition); BulletSharp.Math.Vector3 start = ray.origin.ToBullet(); BulletSharp.Math.Vector3 end = ray.GetPoint(200).ToBullet(); //Creates a callback result that will be updated if we do a ray test with it ClosestRayResultCallback rayResult = new ClosestRayResultCallback(ref start, ref end); //Retrieves the bullet physics world and does a ray test with the given coordinates and updates the callback object BPhysicsWorld world = BPhysicsWorld.Get(); world.world.RayTest(start, end, rayResult); //If there is a collision object and it is a robot part, set that to be new attachment point if (rayResult.CollisionObject != null) { GameObject selectedObject = ((BRigidBody)rayResult.CollisionObject.UserObject).gameObject; if (selectedObject.transform.parent != null && selectedObject.transform.parent.name == "Robot") { if (lastNode != null && !selectedObject.Equals(lastNode)) { RevertNodeColors(lastNode, hoveredColors); lastNode = null; } else { ChangeNodeColors(selectedObject, hoverColor, hoveredColors); lastNode = selectedObject; } if (UnityEngine.Input.GetMouseButtonDown(0)) { string name = selectedObject.name; RevertNodeColors(lastNode, hoveredColors); RevertNodeColors(SelectedNode, selectedColors); SelectedNode = selectedObject; ChangeNodeColors(SelectedNode, selectedColor, selectedColors); UserMessageManager.Dispatch(name + " has been selected as the node for sensor attachment", 5); } } else { if (lastNode != null) { RevertNodeColors(lastNode, hoveredColors); lastNode = null; } if (UnityEngine.Input.GetMouseButtonDown(0)) { UserMessageManager.Dispatch("Please select a robot node!", 3); } } } }
internal RayCastResult(ref ClosestRayResultCallback callback) { var hitPoint = callback.HitPointWorld; var hitNormal = callback.HitNormalWorld; HitObject = callback.CollisionObject?.UserObject as Part; Position = new Vector3(hitPoint.X, hitPoint.Y, hitPoint.Z); Normal = new Vector3(hitNormal.X, hitNormal.Y, hitNormal.Z); }
void FixedUpdate() { BulletSharp.Math.Vector3 from = transform.position.ToBullet(); List <bool> hits = new List <bool>() { false, false, false, false, false }; //float theta = angle * Mathf.PI; //float sin = Mathf.Sin(theta); //float cos = Mathf.Cos(theta); //float tan = Mathf.Tan(theta); var endPos = transform.position + (Vector3.down * (capsule.Height + heightExtension)); for (int whiskerNum = 0; whiskerNum < 5; whiskerNum++) { BulletSharp.Math.Vector3 to; switch (whiskerNum) { case 0: to = endPos.ToBullet(); break; case 1: to = (endPos + (Vector3.forward * whiskerDist)).ToBullet(); break; case 2: to = (endPos + (Vector3.back * whiskerDist)).ToBullet(); break; case 3: to = (endPos + (Vector3.left * whiskerDist)).ToBullet(); break; case 4: to = (endPos + (Vector3.right * whiskerDist)).ToBullet(); break; default: to = endPos.ToBullet(); break; } ClosestRayResultCallback callback = new ClosestRayResultCallback(ref from, ref to); BPhysicsWorld.Get().world.RayTest(from, to, callback); hits[whiskerNum] = callback.HasHit; Debug.DrawLine(from.ToUnity(), to.ToUnity(), callback.HasHit ? Color.green : Color.red); } isGrounded = hits.Contains(true); }
public void Cast(CollisionWorld cw) { #if BATCH_RAYCASTER if (!gBatchRaycaster) { return; } gBatchRaycaster->clearRays(); for (int i = 0; i < NUMRAYS_IN_BAR; i++) { gBatchRaycaster->addRay(source[i], dest[i]); } gBatchRaycaster->performBatchRaycast(); for (int i = 0; i < gBatchRaycaster->getNumRays(); i++) { const SpuRaycastTaskWorkUnitOut& out = (*gBatchRaycaster)[i]; hit[i].setInterpolate3(source[i], dest[i], out.HitFraction); normal[i] = out.hitNormal; normal[i].Normalize(); } #else for (int i = 0; i < NUMRAYS_IN_BAR; i++) { using (var cb = new ClosestRayResultCallback(ref source[i], ref dest[i])) { cw.RayTestRef(ref source[i], ref dest[i], cb); if (cb.HasHit) { hit[i] = cb.HitPointWorld; normal[i] = cb.HitNormalWorld; normal[i].Normalize(); } else { hit[i] = dest[i]; normal[i] = new Vector3(1.0f, 0.0f, 0.0f); } } } frame_counter++; if (frame_counter > 50) { min_ms = ms < min_ms ? ms : min_ms; max_ms = ms > max_ms ? ms : max_ms; sum_ms += ms; sum_ms_samples++; float mean_ms = (float)sum_ms / (float)sum_ms_samples; Console.WriteLine("{0} rays in {1} ms {2} {3} {4}", NUMRAYS_IN_BAR * frame_counter, ms, min_ms, max_ms, mean_ms); ms = 0; frame_counter = 0; } #endif }
/// <summary> /// Casts a ray and returns information about the first object hit /// </summary> /// <param name="origin">The origin of the ray</param> /// <param name="target">The target of the ray</param> /// <returns>A Ray object if the ray hits and Object, null otherwise</returns> public static Ray Cast(Vector3 origin, Vector3 target) { var cb = new ClosestRayResultCallback(origin, target); _app.PhysicsWorld.RayTest(origin, target, cb); if (cb.HasHit) { return(new Ray(cb.CollisionObject.UserObject as GameObject, origin, target, cb.HitPointWorld, cb.HitNormalWorld)); } return(null); }
private void ClickRuler() { //Casts a ray from the camera in the direction the mouse is in and returns the closest object hit Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); BulletSharp.Math.Vector3 start = ray.origin.ToBullet(); BulletSharp.Math.Vector3 end = ray.GetPoint(200).ToBullet(); //Creates a callback result that will be updated if we do a ray test with it ClosestRayResultCallback rayResult = new ClosestRayResultCallback(ref start, ref end); //Retrieves the bullet physics world and does a ray test with the given coordinates and updates the callback object BPhysicsWorld world = BPhysicsWorld.Get(); world.world.RayTest(start, end, rayResult); if (rayResult.CollisionObject != null) { if (Input.GetMouseButtonDown(0)) { if (firstPoint == BulletSharp.Math.Vector3.Zero) { rulerStartPoint.GetComponent <LineRenderer>().enabled = true; rulerStartPoint.GetComponent <LineRenderer>().SetPosition(0, rulerStartPoint.transform.position); rulerEndPoint.SetActive(true); firstPoint = rayResult.HitPointWorld; } else { DisableRuler(); } } if (firstPoint != null) { Debug.DrawRay(firstPoint.ToUnity(), Vector3.up); } if (firstPoint == BulletSharp.Math.Vector3.Zero) { rulerStartPoint.transform.position = rayResult.HitPointWorld.ToUnity(); } else { rulerText.text = Mathf.Round(BulletSharp.Math.Vector3.Distance(firstPoint, rayResult.HitPointWorld) * 328.084f) / 100 + "ft"; rulerXText.text = Mathf.Round(Mathf.Abs(firstPoint.X - rayResult.HitPointWorld.X) * 328.084f) / 100 + "ft"; rulerYText.text = Mathf.Round(Mathf.Abs(firstPoint.Y - rayResult.HitPointWorld.Y) * 328.084f) / 100 + "ft"; rulerZText.text = Mathf.Round(Mathf.Abs(firstPoint.Z - rayResult.HitPointWorld.Z) * 328.084f) / 100 + "ft"; rulerEndPoint.transform.position = rayResult.HitPointWorld.ToUnity(); rulerStartPoint.GetComponent <LineRenderer>().SetPosition(1, rulerEndPoint.transform.position); } } }
public void ExecuteBlastJump() { blastJumpToken = false; handledThisFrame = true; if (!timer.CheckAndReset()) { return; } BulletSharp.Math.Vector3 from = startRaycastFrom.position.ToBullet(); BulletSharp.Math.Vector3 to = (startRaycastFrom.position + startRaycastFrom.forward * maxBlastJumpRange).ToBullet(); ClosestRayResultCallback callback = new ClosestRayResultCallback(ref from, ref to); BPhysicsWorld.Get().world.RayTest(from, to, callback); if (enableDebugMode) { Debug.DrawLine(from.ToUnity(), to.ToUnity(), Color.green, 2f); } if (callback.HasHit) { float force = 0; Vector3 meToGround = callback.HitPointWorld.ToUnity() - transform.position; float dist = meToGround.magnitude; if (dist < maxBlastJumpRange) { //Falloff curve visual: https://www.desmos.com/calculator/plvrrosegp var b = 1f / (Mathf.Pow(maxBlastJumpRange, 2) * smallestBlastForce); force = blastJumpForce / (1 * maxBlastJumpForce + (falloffStrength * Mathf.Abs(dist)) + (b * Mathf.Pow(Mathf.Abs(dist), 2))); } rigidBody.AddImpulse(-meToGround.normalized * force); #region Debug if (enableDebugMode) { Debug.Log("Blasting off with a force of: " + force); var s = GameObject.CreatePrimitive(PrimitiveType.Sphere); s.transform.localScale = Vector3.one * .1f; s.transform.position = callback.HitPointWorld.ToUnity(); s.GetComponent <MeshRenderer>().material.color = Color.green; } #endregion } }
public void Update() { if (Time.frameCount == 10) { BulletSharp.Math.Vector3 fromP = transform.position.ToBullet(); BulletSharp.Math.Vector3 toP = (transform.position + Vector3.down * 10f).ToBullet(); ClosestRayResultCallback callback = new ClosestRayResultCallback(ref fromP, ref toP); BPhysicsWorld world = BPhysicsWorld.Get(); world.world.RayTest(fromP, toP, callback); if (callback.HasHit) { Debug.LogFormat("Hit p={0} n={1} obj{2}", callback.HitPointWorld, callback.HitNormalWorld, callback.CollisionObject.UserObject); } } }
public bool RayCastSingle(Vector3 from, Vector3 to, int filterMask, int filterGroup, ref Vector3 contactPoint, ref Vector3 contactNormal) { bool hasHit = false; ClosestRayResultCallback callback = new ClosestRayResultCallback(from, to); callback.m_collisionFilterGroup = (CollisionFilterGroups)filterGroup; callback.m_collisionFilterMask = (CollisionFilterGroups)filterMask; hasHit = callback.HasHit(); if (hasHit) { contactPoint = callback.m_hitPointWorld; contactNormal = callback.m_hitPointWorld; } return(hasHit); }
private void SelectingNode() { //Casts a ray from the camera in the direction the mouse is in and returns the closest object hit Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); BulletSharp.Math.Vector3 start = ray.origin.ToBullet(); BulletSharp.Math.Vector3 end = ray.GetPoint(200).ToBullet(); //Creates a callback result that will be updated if we do a ray test with it ClosestRayResultCallback rayResult = new ClosestRayResultCallback(ref start, ref end); //Retrieves the bullet physics world and does a ray test with the given coordinates and updates the callback object BPhysicsWorld world = BPhysicsWorld.Get(); world.world.RayTest(start, end, rayResult); //If there is a collision object and it is dynamic and not a robot part, change the gamepiece to that if (rayResult.CollisionObject != null) { string name = (rayResult.CollisionObject.UserObject.ToString().Replace(" (BulletUnity.BRigidBody)", "")); Debug.Log(name); if (rayResult.CollisionObject.CollisionFlags == BulletSharp.CollisionFlags.StaticObject) { RevertNodeColors(hoveredNode, hoveredColors); } else if (GameObject.Find(name) == null) { Debug.Log("DPM: Game object not found"); RevertNodeColors(hoveredNode, hoveredColors); } else if (GameObject.Find(name).transform.parent == transform) { if (hoveredNode != GameObject.Find(name)) { RevertNodeColors(hoveredNode, hoveredColors); } hoveredNode = GameObject.Find(name); ChangeNodeColors(hoveredNode, hoverColor, hoveredColors); } else { RevertNodeColors(hoveredNode, hoveredColors); } } }
/// <summary> /// Allows the user to select a dynamic object with their mouse and add it to the list of gamepieces. /// </summary> public void SetGamepiece(int index) { //Casts a ray from the camera in the direction the mouse is in and returns the closest object hit Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); BulletSharp.Math.Vector3 start = ray.origin.ToBullet(); BulletSharp.Math.Vector3 end = ray.GetPoint(200).ToBullet(); //Creates a callback result that will be updated if we do a ray test with it ClosestRayResultCallback rayResult = new ClosestRayResultCallback(ref start, ref end); //Retrieves the bullet physics world and does a ray test with the given coordinates and updates the callback object BPhysicsWorld world = BPhysicsWorld.Get(); world.world.RayTest(start, end, rayResult); //If there is a collision object and it is dynamic and not a robot part, change the gamepiece to that if (rayResult.CollisionObject != null) { string name = (rayResult.CollisionObject.UserObject.ToString().Replace(" (BulletUnity.BRigidBody)", "")); Debug.Log(name); if (rayResult.CollisionObject.CollisionFlags == BulletSharp.CollisionFlags.StaticObject) { UserMessageManager.Dispatch("The gamepiece must be a dynamic object!", 3); } else if (GameObject.Find(name) == null) { Debug.Log("DPM: Game object not found"); } else if (GameObject.Find(name).transform.parent == transform) { UserMessageManager.Dispatch("You cannot select a robot part as a gamepiece!", 3); } else { gamepieceNames[index] = name.Replace("(Clone)", ""); //gets rid of the clone tag given to spawned gamepieces intakeInteractor[index].SetKeyword(gamepieceNames[index], index); GameObject gamepiece = GameObject.Find(name); UserMessageManager.Dispatch(name + " has been selected as the gamepiece", 2); addingGamepiece = false; } } else { } }
public bool RayCast(Vector3 From, Vector3 To, out Vector3 HitPos, out Vector3 HitNormal, out RigidBody Body) { using (ClosestRayResultCallback RayResult = new ClosestRayResultCallback(ref From, ref To)) { World.RayTestRef(ref From, ref To, RayResult); if (RayResult.HasHit) { HitPos = RayResult.HitPointWorld; HitNormal = RayResult.HitNormalWorld; Body = RayResult.CollisionObject as RigidBody; return(true); } } Body = null; HitPos = HitNormal = Vector3.Zero; return(false); }
/// <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> /// Performs an un-filtered raycast. /// </summary> /// <param name="ray">The ray to perform the cast on.</param> /// <param name="maxLength">The maximum length of the ray.</param> /// <returns></returns> internal RayCastResult FindPartOnRay(Ray ray, float maxLength = 3000) { lock (Locker) { var from = ray.Origin; Vector3 to; Vector3.Multiply(ref ray.Direction, maxLength, out to); Vector3.Add(ref to, ref from, out to); var bulletFrom = new BulletSharp.Math.Vector3(from.x, from.y, from.z); var bulletTo = new BulletSharp.Math.Vector3(to.x, to.y, to.z); var resultCallback = new ClosestRayResultCallback(ref bulletFrom, ref bulletTo); World.RayTest(bulletFrom, bulletTo, resultCallback); return(new RayCastResult(ref resultCallback)); } }
public bool RayPick(OpenTK.Vector3 from, OpenTK.Vector3 to, out OpenTK.Vector3 col) { var bfrom = ToBulletVector3(from); var bto = ToBulletVector3(to); var cfrom = new BulletSharp.Math.Vector3(); var cto = new BulletSharp.Math.Vector3(); ClosestRayResultCallback rayCb = new ClosestRayResultCallback(ref cfrom, ref cto); world.RayTest(bfrom, bto, rayCb); // Lerp로 보간해야 결과가 나온다. var p = BulletSharp.Math.Vector3.Lerp(bfrom, bto, rayCb.ClosestHitFraction); col = ToOpenVector3(p); return(rayCb.HasHit); }
public RayResult FindEntityOnRay(Ray ray, PhysicsEntity ignore = null) { RayResult result = new RayResult(); if (collisionWorld != null) { BulletSharp.Math.Vector3 start = ray.Origin; BulletSharp.Math.Vector3 end = ray.Origin + ray.Direction; ClosestRayResultCallback callback = new ClosestRayResultCallback(ref start, ref end); collisionWorld.RayTest(start, end, callback); if (callback.HasHit && callback.CollisionObject != ignore.Rigidbody) { result.Position = callback.HitPointWorld; result.Normal = callback.HitNormalWorld; //result.Hit = callback.CollisionObject; } } return(result); }
public override bool Raycast(GameSystem.GameCore.SerializableMath.Vector3 startPoint, GameSystem.GameCore.SerializableMath.Vector3 endPoint, out GameSystem.GameCore.SerializableMath.Vector3 hitPoint, out CollisionProxy hitObject, int mask = -1) { // transfer serializable math position to bullet math position BulletSharp.Math.Vector3 start = startPoint.ToBullet(), end = endPoint.ToBullet(); var callback = new ClosestRayResultCallback(ref start, ref end); // set group mask filter callback.CollisionFilterMask = (short)mask; world.RayTest(start, end, callback); if (callback.HasHit) { hitPoint = callback.HitPointWorld.ToSerializable(); hitObject = (CollisionProxy)callback.CollisionObject.UserObject; } else { hitPoint = GameSystem.GameCore.SerializableMath.Vector3.Zero; hitObject = null; } return(callback.HasHit); }
public static bool Raycast(Vector3 source, Vector3 direction, float maxDistance, out RaycastHitInfo info) { BulletVector3 Bdestination = (source + (direction * maxDistance)).ToBullet(); BulletVector3 Bsource = source.ToBullet(); using (var cb = new ClosestRayResultCallback(ref Bsource, ref Bdestination)) { _contextWorld.RayTestRef(ref Bsource, ref Bdestination, cb); if (cb.HasHit) { info = new RaycastHitInfo(cb.HitPointWorld.ToNumerics(), Vector3.Normalize(cb.HitNormalWorld.ToNumerics()), (RigidBodyComponent)cb.CollisionObject.UserObject); return(true); } else { info = new RaycastHitInfo(Bdestination.ToNumerics(), new Vector3(1.0f, 0.0f, 0.0f), null); return(false); } } }
private static void PollSelection(GameWindow window, MouseState mouseState, KeyboardState keyboardState) // TODO: raycast is performed wrong on shapes' edges; check! { var startWorld = RaycastResult.StartWorld.ToBullet3(); var endWorld = RaycastResult.EndWorld.ToBullet3(); using (var raycastCallback = new ClosestRayResultCallback(ref startWorld, ref endWorld)) { PhysicsHandler.RayTestRef(ref startWorld, ref endWorld, raycastCallback); if (/*window.IsMouseButtonPressed(MouseButton.Right)*/ mouseState.IsButtonDown(MouseButton.Right) && _lastState.IsButtonUp(MouseButton.Right)) // TODO: perhaps use Window built-in method? { if (raycastCallback.HasHit) { if (!keyboardState.IsKeyDown(Key.ControlLeft) && SelectedObjects.Find(x => x != raycastCallback.CollisionObject) != null) { // Control is not pressed and other objects are already selected ---> clear selection and add the new object to the selection ClearAndAddSelection(raycastCallback.CollisionObject); } else { // add the object to the selection if it's not there yet if (!SelectedObjects.Contains(raycastCallback.CollisionObject)) { AddSelection(raycastCallback.CollisionObject); } else { RemoveSelection(raycastCallback.CollisionObject); } } } else { // no object is selected ---> clear selection ClearSelection(); } } } }
// Update is called once per frame void Update() { if (ammo > 0 && Input.GetMouseButtonDown(0)) { Ray ray = cam.ScreenPointToRay(Input.mousePosition); BulletSharp.Math.Vector3 fromP = ray.origin.ToBullet(); BulletSharp.Math.Vector3 toP = (ray.direction * 500).ToBullet(); ClosestRayResultCallback callback = new ClosestRayResultCallback(ref fromP, ref toP); BPhysicsWorld world = BPhysicsWorld.Get(); world.world.RayTest(fromP, toP, callback); if (callback.HasHit) { if (callback.CollisionObject.UserObject.GetType().Name == "BRigidBody") { ((BRigidBody)callback.CollisionObject.UserObject).AddImpulse((new Vector3(callback.HitNormalWorld.X, callback.HitNormalWorld.Y, callback.HitNormalWorld.Z)) * -5); } } ammo--; UpdateAmmo(); } }
public void Update() { setrefresh++; if (setrefresh % 10 == 0) { BulletSharp.Math.Vector3 fromP = this.GetParent <Unit>().Position.ToBullet(); BulletSharp.Math.Vector3 toP = (this.GetParent <Unit>().Position + Vector3.down * 10f).ToBullet(); ClosestRayResultCallback callback = new ClosestRayResultCallback(ref fromP, ref toP); BPhysicsWorld world = BPhysicsWorld.Get; world.world.RayTest(fromP, toP, callback); if (callback.HasHit && callback.CollisionObject.UserObject is Unit unit) { Log.Debug("fromp=" + fromP + "||top=" + toP); Log.Debug("Hit p" + callback.HitPointWorld + "N=" + callback.HitNormalWorld + "obj=" + callback.CollisionObject.UserObject); Unit x = unit; } if (setrefresh > 10000) { setrefresh = 0; } } }