/** <summary> * Register a CollisionListener that will receive notifications of collisions. </summary> * <param name="listener"> The listener set to be informed whenever a collision occurs </param> * <returns> Whether the operation was successful </returns> */ public bool Register_collision_listener(CollisionListener listener) { if (listener == null) return false; listeners.Add (listener); return true; }
/// <summary> /// Subscribes a listener to the collisions's events. /// Returns false if the listener was already subscribed. /// </summary> /// <param name="listener">The listener to subscribe</param> /// <returns>If the listener was successfully subscribed</returns> public bool AddListener(CollisionListener listener) { if (_listeners.Contains(listener)) return false; _listeners.Add(listener); return true; }
protected ABCollider(ABRigidBody _body) { RigidBody = _body; CollisionListener = new CollisionListener(this); IsTrigger = false; World.Current.PhysicsWorld.AddCollider(this); }
/// <summary> /// Unsubscribes a listener to the collisions's events. /// Returns false if the listener wasn't subscribed yet. /// </summary> /// <param name="listener">The listener to unsubscribe</param> /// <returns>If the listener was successfully unsubscribed</returns> public bool RemoveListener(CollisionListener listener) { if (!_listeners.Contains(listener)) return false; _listeners.Remove(listener); return true; }
public static IEnumerator rotate( PhysicsRemoteFPSAgentController controller, CollisionListener collisionListener, Transform moveTransform, Quaternion targetRotation, float fixedDeltaTime, float radiansPerSecond, bool returnToStartPropIfFailed = false ) { float degreesPerSecond = radiansPerSecond * 180.0f / Mathf.PI; return(updateTransformPropertyFixedUpdate( controller, collisionListener, moveTransform, targetRotation, // Get (t) => t.rotation, // Set (t, target) => t.rotation = target, // Next (t, target) => Quaternion.RotateTowards(t.rotation, target, fixedDeltaTime * degreesPerSecond), // Direction function for quaternion should just output target quaternion, since RotateTowards is used for addToProp (target, current) => target, // Distance Metric (target, current) => Quaternion.Angle(current, target), fixedDeltaTime, returnToStartPropIfFailed )); }
// debug for static arm collisions from collision listener public void GetMidLevelArmCollisions() { IK_Robot_Arm_Controller arm = getArm(); CollisionListener collisionListener = arm.GetComponentInChildren <CollisionListener>(); if (collisionListener != null) { List <Dictionary <string, string> > collisions = new List <Dictionary <string, string> >(); foreach (var sc in collisionListener.StaticCollisions()) { Dictionary <string, string> element = new Dictionary <string, string>(); if (sc.simObjPhysics != null) { element["objectType"] = "simObjPhysics"; element["name"] = sc.simObjPhysics.objectID; } else { element["objectType"] = "gameObject"; element["name"] = sc.gameObject.name; } collisions.Add(element); } actionFinished(true, collisions); } }
public override void OnInitialize() { base.OnInitialize(); NativeEntity.LoadGeometry(0, "objects/default/primitive_sphere.cgf"); Scale = Vec3.One * 0.5f; collisionListener = AddComponent <CollisionListener>(); collisionListener.OnCollide += OnCollide; }
private void Awake() { m_dragListener = GetComponent <DragListener>(); m_collisionListener = GetComponent <CollisionListener>(); m_rb = GetComponent <Rigidbody>(); m_constantForce = GetComponent <ConstantForce>(); m_constantForce.force = Vector3.zero; m_rb.useGravity = false; }
public static CollisionListener Get(Rigidbody body) { CollisionListener listener = body.GetComponent <CollisionListener>(); if (listener == null) { listener = body.gameObject.AddComponent <CollisionListener>(); } return(listener); }
/// <summary> /// Add a listener which is notified when any collision happens between two /// colliders with the given ColliderTags (the collision filter) /// </summary> public void AddListener(ColliderTag tag1, ColliderTag tag2, CollisionListener listener) { var collisionType = new CollisionFilter(tag1, tag2); if (!listenerMap.ContainsKey(collisionType)) { listenerMap[collisionType] = new List <CollisionListener>(); } listenerMap[collisionType].Add(listener); }
/** <summary> * Register a CollisionListener that will receive notifications of collisions. </summary> * <param name="listener"> The listener set to be informed whenever a collision occurs </param> * <returns> Whether the operation was successful </returns> */ public bool Register_collision_listener(CollisionListener listener) { if (listener == null) { return(false); } listeners.Add(listener); return(true); }
void Start() { armTarget = this.transform .Find("robot_arm_FK_IK_rig") .Find("IK_rig") .Find("IK_pos_rot_manipulator"); // FirstJoint = this.transform.Find("robot_arm_1_jnt"); this is now set via serialize field, along with the other joints handCameraTransform = this.transform.FirstChildOrDefault(x => x.name == "robot_arm_4_jnt"); // calculating based on distance from origin of arm to the 2nd joint, which will always be constant this.originToShoulderLength = Vector3.Distance( this.transform.FirstChildOrDefault( x => x.name == "robot_arm_2_jnt" ).position, this.transform.position ); this.collisionListener = this.GetComponentInParent <CollisionListener>(); List <CapsuleCollider> armCaps = new List <CapsuleCollider>(); List <BoxCollider> armBoxes = new List <BoxCollider>(); // get references to all colliders in arm. Remove trigger colliders so there are no duplicates when using these as reference for // overlap casts since the trigger colliders are themselves duplicates of the nontrigger colliders. armCaps.AddRange(gameObject.GetComponentsInChildren <CapsuleCollider>()); armBoxes.AddRange(gameObject.GetComponentsInChildren <BoxCollider>()); // clean up arm colliders, removing triggers List <CapsuleCollider> cleanedCaps = new List <CapsuleCollider>(); foreach (CapsuleCollider c in armCaps) { if (!c.isTrigger) { cleanedCaps.Add(c); } } ArmCapsuleColliders = cleanedCaps.ToArray(); List <BoxCollider> cleanedBoxes = new List <BoxCollider>(); foreach (BoxCollider b in armBoxes) { if (!b.isTrigger) { cleanedBoxes.Add(b); } } ArmBoxColliders = cleanedBoxes.ToArray(); }
public override void OnInspectorGUI() { CollisionListener script = (CollisionListener)target; bool isWarning = !script.GetComponent <Rigidbody2D>() && !(script.targetObject && script.targetObject.GetComponent <Rigidbody2D>()); if (isWarning) { string warningText = "One of the components must have a Rigidbody2D \n\n For disable physics: \n - GravityScale = 0 \n - IsTrigger = true."; EditorGUILayout.HelpBox(warningText, MessageType.Warning); } base.OnInspectorGUI(); }
/// <summary> /// This will register an event listener with a material pair collision. The event will get called whenever any two bodies /// of those two ID's collide /// NOTE: Not sure if it's limited to a single listener for a material ID pair /// </summary> /// <remarks> /// This is how you get notified of a collision, there is no event off of the body class, you need to get at it from the material /// and filter for the bodies you care about /// /// NOTE: I tested and don't seem to need to register an opposite handler (register with 1,2. No need to also register with 2,1. /// any collision between a 1 and a 2 gets raised) /// </remarks> public void RegisterCollisionEvent(int material1, int material2, EventHandler <MaterialCollisionArgs> callback) { // Create a class that will listen to the newton callback, and turn it into a more c# friendly event CollisionListener listener = new CollisionListener(); listener.Sender = this; listener.Material1 = material1; listener.material2 = material2; listener.EventListener = callback; _collisionListeners.Add(listener); // Register the callback listener.InvokeContactsProcessVariable = new Newton.NewtonContactsProcess(listener.InvokeContactsProcess); // there is a CallbackOnCollectedDelegate exception if newton isn't handed an explicit delegate variable (as opposed to just handing it the method) Newton.NewtonMaterialSetCollisionCallback(_world.Handle, material1, material2, IntPtr.Zero, null, listener.InvokeContactsProcessVariable); }
private static void DoBounce( IHitMapManager hitMapManager, int roomHeightSubPixels, Point collisionPtCartesian, CollisionListener self, ConvexPolygon selfPoly, PositionComponent selfLoc, VelocityComponent selfVelocity, CollisionListener other, ConvexPolygon otherPoly ) { // nothing to do if (selfVelocity.X_SubPixels == 0 && selfVelocity.Y_SubPixels == 0) { return; } var edgeCartesian = ClosestTo(collisionPtCartesian, otherPoly); Vector normOfWallScreen; if (edgeCartesian == null) { // vertex on vertex collision var otherVertex = ClosestVertexTo(collisionPtCartesian, otherPoly); var betweenVerticesCartesian = new LineSegment2D(collisionPtCartesian, otherVertex); var betweenVerticesScreen = TranslateToScreen(roomHeightSubPixels, betweenVerticesCartesian); var wallSlopeScreen = betweenVerticesScreen.Normal(); normOfWallScreen = wallSlopeScreen.Normal(); } else { var edgeScreen = TranslateToScreen(roomHeightSubPixels, edgeCartesian.Value); normOfWallScreen = edgeScreen.Normal(); } // based on: https://gamedev.stackexchange.com/a/23676/155 var curSpeed = new Vector(selfVelocity.X_SubPixels, selfVelocity.Y_SubPixels); var newSpeed = curSpeed - 2 * curSpeed.Dot(normOfWallScreen) * normOfWallScreen; newSpeed = newSpeed.Normalize() * FixedPoint.FromInt(self.DesiredSpeed_HACK); selfVelocity.X_SubPixels = (int)newSpeed.DeltaX; selfVelocity.Y_SubPixels = (int)newSpeed.DeltaY; }
public void MoveAgent( float ahead = 0, float right = 0, float speed = 1, float?fixedDeltaTime = null, bool returnToStart = true, bool disableRendering = true ) { if (ahead == 0 && right == 0) { throw new ArgumentException("Must specify ahead or right!"); } Vector3 direction = new Vector3(x: right, y: 0, z: ahead); float fixedDeltaTimeFloat = fixedDeltaTime.GetValueOrDefault(Time.fixedDeltaTime); CollisionListener collisionListener = this.GetComponentInParent <CollisionListener>(); Vector3 directionWorld = transform.TransformDirection(direction); Vector3 targetPosition = transform.position + directionWorld; collisionListener.Reset(); IEnumerator move = ContinuousMovement.move( controller: this, collisionListener: collisionListener, moveTransform: this.transform, targetPosition: targetPosition, fixedDeltaTime: fixedDeltaTimeFloat, unitsPerSecond: speed, returnToStartPropIfFailed: returnToStart, localPosition: false ); if (disableRendering) { unrollSimulatePhysics( enumerator: move, fixedDeltaTime: fixedDeltaTimeFloat ); } else { StartCoroutine(move); } }
public override void OnAddedToEntity() { //Set type Type = Entity.AddComponent <TypeComponent>(); Type.SetType(EntityType.STATIC_OBJECT); //Set up texture var tex = Entity.Scene.Content.Load <Texture2D>(Source.Properties["SourceTex"]); Sprite = new SpriteRenderer(tex); Entity.AddComponent(Sprite); //Set up collision Collider = Entity.AddComponent <BoxCollider>(); Flags.SetFlagExclusive(ref Collider.CollidesWithLayers, 1); Flags.SetFlagExclusive(ref Collider.PhysicsLayer, 1); CollisionListener = Entity.AddComponent <CollisionListener>(); base.OnAddedToEntity(); }
public override void OnInitialize() { base.OnInitialize(); collisionListener = AddComponent <CollisionListener>(); collisionListener.OnCollide += CollisionListener_OnCollide; NativeEntity.LoadGeometry(0, "objects/default/primitive_sphere.cgf"); var physParams = new SEntityPhysicalizeParams() { density = 1, mass = 10, type = (int)EPhysicalizationType.ePT_Rigid, }; NativeEntity.Physicalize(physParams); }
public static IEnumerator move( PhysicsRemoteFPSAgentController controller, CollisionListener collisionListener, Transform moveTransform, Vector3 targetPosition, float fixedDeltaTime, float unitsPerSecond, bool returnToStartPropIfFailed = false, bool localPosition = false ) { Func <Func <Transform, Vector3>, Action <Transform, Vector3>, Func <Transform, Vector3, Vector3>, IEnumerator> moveClosure = (get, set, next) => updateTransformPropertyFixedUpdate( controller, collisionListener, moveTransform, targetPosition, get, set, next, (target, current) => (target - current).normalized, (target, current) => Vector3.SqrMagnitude(target - current), fixedDeltaTime, returnToStartPropIfFailed ); if (localPosition) { return(moveClosure( (t) => t.localPosition, (t, pos) => t.localPosition = pos, (t, direction) => t.localPosition + direction * unitsPerSecond * fixedDeltaTime )); } else { return(moveClosure( (t) => t.position, (t, pos) => t.position = pos, (t, direction) => t.position + direction * unitsPerSecond * fixedDeltaTime )); } }
private static void continuousMoveFinish <T>( PhysicsRemoteFPSAgentController controller, CollisionListener collisionListener, Transform moveTransform, System.Action <Transform, T> setProp, T target, T resetProp ) { bool actionSuccess = true; string debugMessage = ""; IK_Robot_Arm_Controller arm = controller.GetComponentInChildren <IK_Robot_Arm_Controller>(); var staticCollisions = collisionListener.StaticCollisions(); if (staticCollisions.Count > 0) { var sc = staticCollisions[0]; // decide if we want to return to original property or last known property before collision setProp(moveTransform, resetProp); // if we hit a sim object if (sc.isSimObj) { debugMessage = "Collided with static sim object: '" + sc.simObjPhysics.name + "', could not reach target: '" + target + "'."; } // if we hit a structural object that isn't a sim object but still has static collision if (!sc.isSimObj) { debugMessage = "Collided with static structure in scene: '" + sc.gameObject.name + "', could not reach target: '" + target + "'."; } actionSuccess = false; } controller.errorMessage = debugMessage; controller.actionFinished(actionSuccess, debugMessage); }
public override void OnContext(System.Object context) { base.OnContext(context); collisionProcessor = new CollisionProcessor(); GameObject voxelCharacter = GameObject.Instantiate(ResourceManager.Instance.LoadAsset <UnityEngine.Object> ("Characters/VoxelGirl/MainCharacter")) as GameObject; if (voxelCharacter == null) { QLogger.LogErrorAndThrowException("VoxelGirl is not instantiated"); } // Main.Instance.uIManager = uiManagerGo.GetComponent<UIManager>(); // if ( Main.Instance.uIManager == null ) QLogger.LogErrorAndThrowException ( "UiManager script was not instantiated"); player = new iPlayer(); CharacterController controller = new CharacterController(); controller.Init(voxelCharacter, player); WeaponController weaponController = new WeaponController(); player.Init(controller, weaponController); CollisionListener playerCollisionListener = voxelCharacter.GetComponentInChildren <CollisionListener>(); Core.QLogger.Assert(playerCollisionListener != null); playerCollisionListener.Init(collisionProcessor.ProcessCollision, player); cameraScript = GameObject.Find("ThirdPersonCamera").GetComponent <ThirdPersonCamera>(); cameraScript.SetCharacterToFollow(voxelCharacter.transform); player.EquipWeapon(eInventoryItem.Pistol); Core.Updater.Instance.FixedUpdater += FixedUpdate; Core.Updater.Instance.LateUpdater += LateUpdate; }
public void RotateAgent( float degrees, float speed = 1.0f, bool waitForFixedUpdate = false, bool returnToStart = true, bool disableRendering = true, float fixedDeltaTime = 0.02f ) { CollisionListener collisionListener = this.GetComponentInParent <CollisionListener>(); collisionListener.Reset(); // this.transform.Rotate() IEnumerator rotate = ContinuousMovement.rotate( controller: this, collisionListener: this.GetComponentInParent <CollisionListener>(), moveTransform: this.transform, targetRotation: this.transform.rotation * Quaternion.Euler(0.0f, degrees, 0.0f), fixedDeltaTime: disableRendering ? fixedDeltaTime : Time.fixedDeltaTime, radiansPerSecond: speed, returnToStartPropIfFailed: returnToStart ); if (disableRendering) { unrollSimulatePhysics( enumerator: rotate, fixedDeltaTime: fixedDeltaTime ); } else { StartCoroutine(rotate); } }
/// <summary> Add a listener to be notified of collisions /// /// </summary> /// <param name="listener">The listener to be notified of collisions /// </param> public virtual void AddListener(CollisionListener listener) { listeners.Add(listener); }
/// <summary> /// This will register an event listener with a material pair collision. The event will get called whenever any two bodies /// of those two ID's collide /// NOTE: Not sure if it's limited to a single listener for a material ID pair /// </summary> /// <remarks> /// This is how you get notified of a collision, there is no event off of the body class, you need to get at it from the material /// and filter for the bodies you care about /// /// NOTE: I tested and don't seem to need to register an opposite handler (register with 1,2. No need to also register with 2,1. /// any collision between a 1 and a 2 gets raised) /// </remarks> public void RegisterCollisionEvent(int material1, int material2, EventHandler<MaterialCollisionArgs> callback) { // Create a class that will listen to the newton callback, and turn it into a more c# friendly event CollisionListener listener = new CollisionListener(); listener.Sender = this; listener.Material1 = material1; listener.material2 = material2; listener.EventListener = callback; _collisionListeners.Add(listener); // Register the callback listener.InvokeContactsProcessVariable = new Newton.NewtonContactsProcess(listener.InvokeContactsProcess); // there is a CallbackOnCollectedDelegate exception if newton isn't handed an explicit delegate variable (as opposed to just handing it the method) Newton.NewtonMaterialSetCollisionCallback(_world.Handle, material1, material2, IntPtr.Zero, null, listener.InvokeContactsProcessVariable); }
/// <summary> /// Metodo para ayudar a registrar un listener de un cuerpo en particular mas facilmente. /// Igual se pueden usar los addCollisionListener del eventManager pero es mas recomendado /// agregarlos desde aca si son para un cuerpo en particular. /// </summary> /// <param name="listener"></param> public void addCollisionListener(CollisionListener listener) { EventManager.Instance.addCollisionListener(this.owner, this.id, listener); }
public static IEnumerator updateTransformPropertyFixedUpdate <T>( PhysicsRemoteFPSAgentController controller, CollisionListener collisionListener, Transform moveTransform, T target, Func <Transform, T> getProp, Action <Transform, T> setProp, Func <Transform, T, T> nextProp, // We could remove this one, but it is a speedup to not compute direction for position update calls at every addToProp call and just outside while Func <T, T, T> getDirection, Func <T, T, float> distanceMetric, float fixedDeltaTime, bool returnToStartPropIfFailed, double epsilon = 1e-3 ) { T originalProperty = getProp(moveTransform); var previousProperty = originalProperty; var arm = controller.GetComponentInChildren <IK_Robot_Arm_Controller>(); var ikSolver = arm.gameObject.GetComponentInChildren <FK_IK_Solver>(); // commenting out the WaitForEndOfFrame here since we shoudn't need // this as we already wait for a frame to pass when we execute each action // yield return yieldInstruction; var currentProperty = getProp(moveTransform); float currentDistance = distanceMetric(target, currentProperty); T directionToTarget = getDirection(target, currentProperty); while (currentDistance > epsilon && collisionListener.StaticCollisions().Count == 0) { previousProperty = getProp(moveTransform); T next = nextProp(moveTransform, directionToTarget); float nextDistance = distanceMetric(target, next); // allows for snapping behaviour to target when the target is close // if nextDistance is too large then it will overshoot, in this case we snap to the target // this can happen if the speed it set high if ( nextDistance <= epsilon || nextDistance > distanceMetric(target, getProp(moveTransform)) ) { setProp(moveTransform, target); } else { setProp(moveTransform, next); } // this will be a NOOP for Rotate/Move/Height actions ikSolver.ManipulateArm(); if (!Physics.autoSimulation) { Physics.Simulate(fixedDeltaTime); } yield return(new WaitForFixedUpdate()); currentDistance = distanceMetric(target, getProp(moveTransform)); } T resetProp = previousProperty; if (returnToStartPropIfFailed) { resetProp = originalProperty; } continuousMoveFinish( controller, collisionListener, moveTransform, setProp, target, resetProp ); // we call this one more time in the event that the arm collided and was reset ikSolver.ManipulateArm(); if (!Physics.autoSimulation) { Physics.Simulate(fixedDeltaTime); } }
public override void OnAddedToEntity() { #region Load up texture atlas... //Load up character texture atlas var idleTexture = Entity.Scene.Content.Load <Texture2D>(Content.Textures.HeroIdle); var runTexture = Entity.Scene.Content.Load <Texture2D>(Content.Textures.HeroRun); var attackTexture = Entity.Scene.Content.Load <Texture2D>(Content.Textures.HeroAttack); var jumpTexture = Entity.Scene.Content.Load <Texture2D>(Content.Textures.HeroJump); var fallTexture = Entity.Scene.Content.Load <Texture2D>(Content.Textures.HeroFall); var idleSprite = Sprite.SpritesFromAtlas(idleTexture, 50, 37); var runSprite = Sprite.SpritesFromAtlas(runTexture, 50, 37); var attackSprite = Sprite.SpritesFromAtlas(attackTexture, 50, 37); var jumpSprite = Sprite.SpritesFromAtlas(jumpTexture, 50, 37); var fallSprite = Sprite.SpritesFromAtlas(fallTexture, 50, 37); #endregion Load up texture atlas... #region add componentents... //Movement component var map = Entity.Scene as SandBoxScene; Mover = Entity.AddComponent(new TiledMapMover(map.TiledMap.GetLayer <TmxLayer>("main"))); //animator component Animator = Entity.AddComponent <SpriteAnimator>(); //Set up collider Collider = Entity.AddComponent <BoxCollider>(); Collider.Width = 16; Collider.Height = 30; Collider.SetLocalOffset(new Vector2(0, 3)); Flags.SetFlagExclusive(ref Collider.CollidesWithLayers, 1); Flags.SetFlagExclusive(ref Collider.PhysicsLayer, 1); //CollisionListener CollisionListener = Entity.AddComponent <CollisionListener>(); //SetType Type = Entity.AddComponent <TypeComponent>(); Type.SetType(EntityType.PLAYER); //Set up StateMachine StateMachine = Entity.AddComponent(new StateMachine()); StateMachine.AddState(STATES.PLAYER_FREE, new PlayerPlatformerStateFree(this)); StateMachine.AddState(STATES.PLAYER_ATTACK, new PlayerStateAttack(this)); StateMachine.CurrentState = STATES.PLAYER_FREE; //Set up Camera var camera = new FollowCamera(Entity); camera.MapLockEnabled = true; Entity.AddComponent(camera); var renderer = new DefaultRenderer(camera: camera.Camera); Entity.Scene.AddRenderer(renderer); //camera.Camera.Position = Entity.Transform.Position; camera.MapSize = new Vector2(1280, 0); camera.FollowLerp = .3f; #endregion add componentents... #region Animations... Animator.AddAnimation("IdleSheathed", 3.5f, new[] { idleSprite[0], idleSprite[1], idleSprite[2], idleSprite[3] }); Animator.AddAnimation("IdleUnSheathed", 3.5f, new[] { idleSprite[4], idleSprite[5], idleSprite[6], idleSprite[7] }); Animator.AddAnimation("RunSheathed", 7.5f, new[] { runSprite[0], runSprite[1], runSprite[2], runSprite[3], runSprite[4], runSprite[5] }); Animator.AddAnimation("RunUnSheathed", 7.5f, new[] { runSprite[6], runSprite[7], runSprite[8], runSprite[9], runSprite[10], runSprite[11] }); Animator.AddAnimation("Attack0", 12, new[] { attackSprite[0], attackSprite[1], attackSprite[2], attackSprite[3], attackSprite[4], attackSprite[5], }); Animator.AddAnimation("Attack1", 12, new[] { attackSprite[6], attackSprite[7], attackSprite[8], attackSprite[9], attackSprite[10] }); Animator.AddAnimation("Attack2", 12, new[] { attackSprite[11], attackSprite[12], attackSprite[13], attackSprite[14], attackSprite[15], attackSprite[16] }); Animator.AddAnimation("Jump", 15, new[] { //jumpSprite[0], //jumpSprite[1], jumpSprite[2], jumpSprite[3] }); Animator.AddAnimation("Fall", 8, new[] { fallSprite[0], fallSprite[1] }); #endregion Animations... //Set up Input SetupInput(); base.OnAddedToEntity(); }
public void setCollisionListener(CollisionListener listener) { this.listener = listener; }
/// <summary> Remove a listener from the space /// /// </summary> /// <param name="listener">The listener to be removed /// </param> public virtual void RemoveListener(CollisionListener listener) { listeners.Remove(listener); }
public static void SubscribeToCollision(GameObject g, CollisionListener listener) { GetOrAddScript(g).colListeners.Add(listener); }
public virtual void OnCollision(CollisionEventArgs e) { CollisionListener?.Invoke(e); }