示例#1
0
        void FixedUpdate()
        {
            return;

            if (isDragging && canvasBoard.canvasBoardBasis.drawingState == DrawingState.Edit)
            {
                //if (lineData != null && lineData.line.lineType == SpringGUI.LineType.Indoor) {
                var filter     = new ContactFilter2D();
                var hitResults = new RaycastHit2D[20];

                filter.useLayerMask = true;
                filter.useTriggers  = true;
                filter.layerMask    = LayerMaskExtensions.Create("UI");

                LineController targetLineCtrl = null;
                RaycastHit2D   hit;

                Vector2 origin    = transform.parent.TransformPoint(rectTransform.anchoredPosition + new Vector2(0, 11f));
                Vector2 direction = Vector2.up;

                int hitCount = Physics2D.Raycast(origin, direction, filter, hitResults, Mathf.Infinity);
                Debug.Log("hitCount: " + hitCount);
                Debug.DrawRay(origin, direction * 1000f, Color.cyan);

                //hit = Physics2D.Raycast (origin, direction);
                //if(hit.collider != null) {
                //    Debug.Log ("hit distance" + hit.distance);
                //Debug.DrawRay (origin, direction * hit.distance, Color.red);
                //}
                //}
            }
        }
示例#2
0
 public virtual void SetDestination()
 {
     if (!rigid.useGravity)
     {
         destination = initPosition + Random.onUnitSphere * Random.value * patrolRange;
         return;
     }
     do
     {
         destination = initPosition + (Random.insideUnitCircle * patrolRange).XYToXZ();
         RaycastHit hit;
         if (Physics.Raycast(destination.SetY(trs.position.y + patrolRange), Vector3.down, out hit, Mathf.Infinity, whatIsLand.AddToMask(whatIsWater)))
         {
             bool shouldReturn = true;
             if (!patrolLand && LayerMaskExtensions.MaskContainsLayer(whatIsLand, hit.collider.gameObject.layer))
             {
                 shouldReturn = false;
             }
             else if (!patrolWater && LayerMaskExtensions.MaskContainsLayer(whatIsWater, hit.collider.gameObject.layer))
             {
                 shouldReturn = false;
             }
             if (shouldReturn)
             {
                 return;
             }
         }
     } while (true);
 }
示例#3
0
        void OnTriggerEnter(Collider collider)
        {
            if (prop.isPickedUp)
            {
                return;
            }
            if (!LayerMaskExtensions.Contains(characterLayers, collider.gameObject.layer))
            {
                return;
            }

            characterPuppet = collider.GetComponent <CharacterPuppet>();
            if (characterPuppet == null)
            {
                return;
            }

            if (characterPuppet.puppet.state != BehaviourPuppet.State.Puppet)
            {
                return;
            }

            if (characterPuppet.propRoot == null)
            {
                return;
            }
            if (characterPuppet.propRoot.currentProp != null)
            {
                return;
            }

            characterPuppet.propRoot.currentProp = prop;
        }
		// Calculating the impulse magnitude from a collision
		private float GetImpulse(MuscleCollision m) {
			float i = m.collision.impulse.sqrMagnitude;

			// Collision threshold
			if (collisionThreshold > 0f) {
				float mlp = PuppetMasterSettings.instance != null? (1f + PuppetMasterSettings.instance.currentlyActivePuppets * PuppetMasterSettings.instance.activePuppetCollisionThresholdMlp): 1f;
				if (i < collisionThreshold * mlp) return 0f;
			}

			i *= 0.04f; // Coeficient for evening out for pre-0.3 versions

			// Collision resistance multipliers
			foreach (CollisionResistanceMultiplier crm in collisionResistanceMultipliers) {
				if (LayerMaskExtensions.Contains(crm.layers, m.collision.collider.gameObject.layer)) {
					if (crm.multiplier <= 0f) i = Mathf.Infinity;
					else i /= crm.multiplier;
					break;
				}
			}
			/*
			// MuscleProps collision resistance multipliers
			BehaviourPuppet.MuscleProps props = GetProps(puppetMaster.muscles[m.muscleIndex].props.group);
			foreach (CollisionResistanceMultiplier crm in props.collisionResistanceMultipliers) {
				if (LayerMaskExtensions.Contains(crm.layers, m.collision.collider.gameObject.layer)) {
					Debug.Log("Here");
					if (crm.multiplier <= 0f) i = Mathf.Infinity;
					else i /= crm.multiplier;
					break;
				}
			}
			*/
			
			return i;
		}
示例#5
0
        // Calculating the impulse magnitude from a collision
        private float GetImpulse(MuscleCollision m, ref float layerThreshold)
        {
            float i = m.collision.impulse.sqrMagnitude;

            i /= puppetMaster.muscles [m.muscleIndex].rigidbody.mass;
            i *= 0.3f;             // Coeficient for evening out for pre-0.3 versions

            // Collision resistance multipliers
            foreach (CollisionResistanceMultiplier crm in collisionResistanceMultipliers)
            {
                if (LayerMaskExtensions.Contains(crm.layers, m.collision.collider.gameObject.layer))
                {
                    if (crm.multiplier <= 0f)
                    {
                        i = Mathf.Infinity;
                    }
                    else
                    {
                        i /= crm.multiplier;
                    }

                    layerThreshold = crm.collisionThreshold;

                    break;
                }
            }

            return(i);
        }
示例#6
0
        // Calculating the impulse magnitude from a collision
        private float GetImpulse(MuscleCollision m)
        {
            float i = m.collision.impulse.sqrMagnitude;

            // Collision threshold
            if (collisionThreshold > 0f)
            {
                float mlp = PuppetMasterSettings.instance != null? (1f + PuppetMasterSettings.instance.currentlyActivePuppets * PuppetMasterSettings.instance.activePuppetCollisionThresholdMlp): 1f;
                if (i < collisionThreshold * mlp)
                {
                    return(0f);
                }
            }

            i *= 0.04f;             // Coeficient for evening out for pre-0.3 versions

            // Collision resistance multipliers
            foreach (CollisionResistanceMultiplier crm in collisionResistanceMultipliers)
            {
                if (LayerMaskExtensions.Contains(crm.layers, m.collision.collider.gameObject.layer))
                {
                    if (crm.multiplier <= 0f)
                    {
                        i = Mathf.Infinity;
                    }
                    else
                    {
                        i /= crm.multiplier;
                    }
                    break;
                }
            }

            return(i);
        }
示例#7
0
    void DoTests()
    {
        LayerMask op    = LayerMask.GetMask(Layers.Default, Layers.Entity, Layers.Trigger);
        LayerMask other = LayerMask.GetMask(Layers.UI, Layers.Water);

        LayerMaskExtensions.CombineMasks(op, other);
    }
 private void Awake()
 {
     _moveRigidbody  = GetComponent <MoveRigidbody>();
     _spriteRenderer = GetComponent <SpriteRenderer>();
     _collider       = GetComponent <Collider2D>();
     _layerMask      = LayerMaskExtensions.GetMaskOrThrow("Platforms", "Items");
 }
示例#9
0
 private void OnPreMuscleCollisionExit(MuscleCollision c)
 {
     if (!LayerMaskExtensions.Contains(groundLayers, c.collision.gameObject.layer))
     {
         return;
     }
     groundContacts[c.muscleIndex]      = false;
     groundContactPoints[c.muscleIndex] = Vector3.zero;
 }
示例#10
0
 	void Start()
 	{
 		LayerMask mask = LayerMaskExtensions.Create("Ignore Raycast", "TransparentFX", "Water");
 		Debug.Log(mask.MaskToString()); //prints out Ignore Raycast, TransparentFX, Water
  
 		mask = mask.RemoveFromMask("TransparentFX");
 		Debug.Log(mask.MaskToString()); //prints out Ignore Raycast, Water
  
 		mask = mask.AddToMask("TransparentFX");
 		Debug.Log(mask.MaskToString()); //prints out Ignore Raycast, TransparentFX, Water
  
 		Debug.Log(mask.Inverse().MaskToString()); //prints out everything except Ignore Raycast, TransparentFX, Water
 	}
示例#11
0
    void DoIgnore()
    {
        // does not change any instance values.
        output = LayerMaskExtensions.FilterMask(mask1, ignoreMask);

        output.SetMask("Nothing");

        // another way to write it but changes outputs value.
        output.Combine(mask1).IgnoreFlagsInMask(ignoreMask);

        //if we wanted mask1 to be updated with the new mask instead, we can do something like this.
        mask1.IgnoreFlagsInMask(ignoreMask);
    }
示例#12
0
    void DoCombine()
    {
        // static CombineMasks creates a new mask from any number of existing masks.
        output = LayerMaskExtensions.CombineMasks(maskToCombine1, MasktoCombine2);

        output.SetMask("Nothing");
        //or

        // Updates this LayerMask with any number of other layerMasks.
        output.Combine(maskToCombine1, MasktoCombine2);
        //or

        //if we wanted maskToCombine1 to be updated with the new mask instead, we can do something like this.
        maskToCombine1.Combine(MasktoCombine2);
    }
示例#13
0
        private void ProcessCollisionEvent(Collision collision, CollisionEventBroadcaster broadcaster)
        {
            if (collision.collider.transform.root == transform)
            {
                return;
            }
            if (!LayerMaskExtensions.Contains(collisionLayers, collision.collider.gameObject.layer))
            {
                return;
            }

            foreach (Group group in groups)
            {
                group.TryDamage(collision, broadcaster);
            }
        }
示例#14
0
    void DoNewMask()
    {
        LayerMask value;

        //using Layer Names. (Default Unity)
        value = LayerMask.GetMask(Layers.Trigger, Layers.Entity, Layers.Default);

        //or for an empty mask;
        value = 0;

        //or

        // using Layer Masks (this is probably a little faster).
        value = LayerMaskExtensions.CombineMasks(Layers.TriggerMask, Layers.EntityMask, Layers.DefaultMask);

        output = value;
    }
示例#15
0
        private void OnPreMuscleCollision(MuscleCollision c)
        {
            if (!LayerMaskExtensions.Contains(groundLayers, c.collision.gameObject.layer))
            {
                return;
            }
            if (c.collision.contacts.Length == 0)
            {
                return;
            }
            lastGroundedTime = Time.time;

            groundContacts[c.muscleIndex] = true;
            if (mode == Mode.CenterOfPressure)
            {
                groundContactPoints[c.muscleIndex] = GetCollisionCOP(c.collision);
            }
        }
示例#16
0
		// When a muscle collides with something (called by the MuscleCollisionBroadcaster component on the muscle).
		protected override void OnMuscleCollisionBehaviour(MuscleCollision m) {
			// All the conditions for ignoring this
			if (!enabled) return;
			if (state == State.Unpinned) return;
			if (collisions > maxCollisions) return;
			if (!LayerMaskExtensions.Contains(collisionLayers, m.collision.gameObject.layer)) return;
			if (masterProps.normalMode == NormalMode.Kinematic && !puppetMaster.isActive && !masterProps.activateOnStaticCollisions && m.collision.gameObject.isStatic) return;

			// Get the collision impulse on the muscle
			float impulse = GetImpulse(m);
			if (impulse <= 0f) return;
			collisions ++;

			// Try to find out if it collided with another puppet's muscle
			if (m.collision.collider.attachedRigidbody != null) {	
				broadcaster = m.collision.collider.attachedRigidbody.GetComponent<MuscleCollisionBroadcaster>();
				if (broadcaster != null) {
					if (broadcaster.muscleIndex < broadcaster.puppetMaster.muscles.Length) {
						// Multiply impulse (if the other muscle has been boosted)
						impulse *= broadcaster.puppetMaster.muscles[broadcaster.muscleIndex].state.impulseMlp;

						float stayF = m.isStay? 0.05f: 0.1f;
						broadcaster.puppetMaster.muscles[broadcaster.muscleIndex].offset -= m.collision.impulse * Time.deltaTime * stayF;

						/*
						float velocityF = puppetMaster.muscles[m.muscleIndex].rigidbody.velocity.sqrMagnitude / broadcaster.puppetMaster.muscles[broadcaster.muscleIndex].rigidbody.velocity.sqrMagnitude;
						velocityF = Mathf.Clamp(velocityF, 0.5f, 2f);
						//velocityF = 1f + (velocityF - 1f) * 0.5f;
						impulse /= velocityF;
						*/
					}
				}
			}

			// Should we activate the puppet?
			if (Activate(m.collision, impulse)) puppetMaster.mode = PuppetMaster.Mode.Active;

			// Let other scripts know about the collision
			if (OnCollisionImpulse != null) OnCollisionImpulse(m, impulse);

			// Unpin the muscle (and other muscles)
			UnPin(m.muscleIndex, impulse);
		}
示例#17
0
        void Awake()
        {
            puppetMaster = GetComponent <PuppetMaster>();

            // Assign the ragdoll layers.
            puppetMaster.gameObject.layer = ragdollLayer;

            foreach (Muscle m in puppetMaster.muscles)
            {
                if (m.joint == null)
                {
                }
                else
                {
                    m.joint.gameObject.layer = ragdollLayer;
                }
            }

            // Assign the character controller layer
            characterController.gameObject.layer = characterControllerLayer;

            // Ignore collisions between the ragdoll and the character controller
            Physics.IgnoreLayerCollision(characterControllerLayer, ragdollLayer);

            // Ignore collisions between character controllers
            Physics.IgnoreLayerCollision(characterControllerLayer, characterControllerLayer);

            // Ignore collisions between the puppet-damaging layers and the character controller layer
            int[] characterIgnoreIndexes = LayerMaskExtensions.MaskToNumbers(ignoreCollisionWithCharacterController);
            foreach (int index in characterIgnoreIndexes)
            {
                Physics.IgnoreLayerCollision(characterControllerLayer, index);
            }

            // Ignore collisions between the ragdoll and the ignoreCollisionWithRagdoll layers
            int[] ragdollIgnoreIndexes = LayerMaskExtensions.MaskToNumbers(ignoreCollisionWithRagdoll);
            foreach (int index in ragdollIgnoreIndexes)
            {
                Physics.IgnoreLayerCollision(ragdollLayer, index);
            }

            Destroy(this);
        }
示例#18
0
        private void ProcessCollision(Collision c)
        {
            if (!LayerMaskExtensions.Contains(layers, c.gameObject.layer))
            {
                return;
            }

            Vector3 collisionCenter = Vector3.zero;

            for (int i = 0; i < c.contacts.Length; i++)
            {
                collisionCenter += c.contacts[i].point;
            }

            collisionCenter /= c.contacts.Length;

            P += collisionCenter;            // * pressure // TODO process each collision based on its pressure

            count++;
            inContact = true;
        }
示例#19
0
    private bool IsTestLocationValid_NavMesh(Vector3 testPos)
    {
        NavMeshHit         hit;
        NavMeshQueryFilter filter = new NavMeshQueryFilter();

        filter.areaMask    = NavMesh.AllAreas;
        filter.agentTypeID = GameObject.FindGameObjectWithTag("NavMeshBuildings").GetComponent <NavMeshSurface2d>().agentTypeID;
        NavMesh.SamplePosition(testPos, out hit, 0.1f, filter);
        bool[] layersFound = LayerMaskExtensions.HasLayers(hit.mask);

        if (layersFound[0])
        {
            //Debug.Log($"0 is good at {testPos}");
            return(true);
        }
        else
        {
            //Debug.Log($"Invalid at {testPos}");
            return(false);
        }
    }
示例#20
0
        void OnTriggerEnter(Collider collider)
        {
            if (prop.isPickedUp)
            {
                return;
            }

            if (!LayerMaskExtensions.Contains(characterLayers, collider.gameObject.layer))
            {
                return;
            }

            PAB = collider.GetComponent <Player_Attack_Behavior>();

            if (PAB == null)
            {
                return;
            }

            //if (PAB.puppet.state != BehaviourPuppet.State.Puppet) return; // don't know what is this for

            if (PAB.PropRootLeft == null || PAB.PropRootRight == null)
            {
                return;                                                         //  if PropRoot did not assign prop script
            }
            if (PAB.PropRootLeft.currentProp != null && PAB.PropRootRight.currentProp != null)
            {
                return;                                 //  if both hand had been occupied
            }
            if (PAB.PropRootRight.currentProp == null)  //  if right hand is free
            {
                PAB.PropRootRight.currentProp = prop;
            }
            else if (PAB.PropRootLeft.currentProp == null)  //  if left hand is free
            {
                PAB.PropRootLeft.currentProp = prop;
            }
        }
示例#21
0
 public void RetrieveObjectsInAreaNonAloc(Rect area, LayerMask mask, ref T[] returnedObjects, ref int count)
 {
     if (m_depth == 0)
     {
         count = 0;
     }
     if (rectOverlap(m_bounds, area))
     {
         for (int i = 0; i < m_storedObjects.Count && returnedObjects.Length > count; i++)
         {
             if (ContainsRect(m_storedObjects[i].bounds) && LayerMaskExtensions.Contains(mask, m_storedObjects[i].Layer))
             {
                 returnedObjects[count++] = m_storedObjects[i];
             }
         }
         if (cells[0] != null)
         {
             for (int i = 0; i < cells.Length && returnedObjects.Length > count; i++)
             {
                 cells[i].RetrieveObjectsInAreaNonAloc(area, mask, ref returnedObjects, ref count);
             }
         }
     }
 }
示例#22
0
    // Update is called once per frame
    void Update()
    {
        //Debug.Log("agent id is" + );

        mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        mousePos = new Vector3(mousePos.x, mousePos.y, 0);
        NavMeshHit         hit;
        NavMeshQueryFilter filter = new NavMeshQueryFilter();

        filter.areaMask    = NavMesh.AllAreas;
        filter.agentTypeID = GameObject.FindGameObjectWithTag("NavMeshSurface").GetComponent <NavMeshSurface2d>().agentTypeID; //-1372625422;
        NavMesh.SamplePosition(mousePos, out hit, 0.1f, filter);
        bool[] layersFound = LayerMaskExtensions.HasLayers(hit.mask);

        mousePositionText.text = mousePos.ToString();
        for (int i = 0; i < layerTexts.Length; i++)
        {
            layerTexts[i].enabled = layersFound[i];
        }

        Debug.DrawLine(mousePos, mousePos + Vector3.one, Color.yellow);
        Debug.DrawLine(mousePos, mousePos - Vector3.left, Color.yellow);

        int        layerMask_calc = 1 << layerMask;
        Collider2D rchit          = Physics2D.OverlapCircle(mousePos, 0.3f, 1 << 8);

        if (rchit)
        {
            foundPhysicsObstacleText.text = rchit.transform.gameObject.name + " at " + rchit.transform.position;
            Debug.DrawLine(mousePos, rchit.transform.position, Color.yellow);
        }
        if (!rchit)
        {
            foundPhysicsObstacleText.text = "no obstacle here";
        }
    }
    void VerticalCollisions(ref Vector2 moveAmount)
    {
        float directionY = Mathf.Sign(moveAmount.y);
        float rayLength  = Mathf.Abs(moveAmount.y) + skinWidth;

        //if falling through platforms, remove oneWayPlatform layer from the mask.
        LayerMask adjustedMaskVertical = collisionMask;

        if (collisions.fallingThroughPlatform)
        {
            adjustedMaskVertical = LayerMaskExtensions.RemoveFromMask(adjustedMaskVertical, oneWayPlatformLayer);
            Debug.Log(adjustedMaskVertical.ToString());
        }

        for (int i = 0; i < verticalRayCount; i++)
        {
            Vector2 rayOrigin = (directionY == -1)?raycastOrigins.bottomLeft:raycastOrigins.topLeft;
            rayOrigin += Vector2.right * (verticalRaySpacing * i + moveAmount.x);
            RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up * directionY, rayLength, adjustedMaskVertical);

            //Debug.DrawRay(rayOrigin, Vector2.up * directionY / 2, Color.white);
            Debug.DrawRay(rayOrigin, Vector2.up * directionY * rayLength, Color.red);

            if (hit)
            {
                //if the Layer matches the name of the OneWayPlatformLayer, then ignore it when going up.
                if (LayerMask.LayerToName(hit.collider.gameObject.layer) == oneWayPlatformLayer)
                {
                    if (directionY == 1 || hit.distance == 0)
                    {
                        continue;
                    }

                    //BUG:

                    //disregard hits if falling through platform.
                    //if (collisions.fallingThroughPlatform) {
                    //continue;
                    //}

                    //if the player inputs down, will pass through oneway platforms briefly.
                    if (m_playerInput.y == -1)
                    {
                        collisions.fallingThroughPlatform = true;
                        Invoke("ResetFallingThroughPlatform", .5f);
                        continue;
                    }
                }

                //main collision property
                moveAmount.y = (hit.distance - skinWidth) * directionY;
                rayLength    = hit.distance;

                if (collisions.climbingSlope)
                {
                    Debug.Log("Vertical Collisions Climbing Slope moveAmountX mod");
                    moveAmount.x = moveAmount.y / Mathf.Tan(collisions.slopeAngle * Mathf.Deg2Rad) * Mathf.Sign(moveAmount.x);
                }

                collisions.below = directionY == -1;
                collisions.above = directionY == 1;
            }
        }
    }
示例#24
0
 private void Awake()
 {
     _myCollider = GetComponent <Collider2D>();
     Assert.AreNotEqual(referencePoints.Length, 0, "CharacterGrounding needs at least one reference point");
     _layerMask = LayerMaskExtensions.GetMaskOrThrow("Platforms", "Items");
 }
示例#25
0
 private bool ValidateCollider(UnityEngine.Collider other)
 {
     return(LayerMaskExtensions.HasLayer(layerMask, other.gameObject.layer) &&
            (string.IsNullOrEmpty(m_tag) || m_tag.GetHashCode() == Constants.UntaggedHash || other.CompareTag(m_tag)));
 }
示例#26
0
        // When a muscle collides with something (called by the MuscleCollisionBroadcaster component on the muscle).
        protected override void OnMuscleCollisionBehaviour(MuscleCollision m)
        {
            if (OnCollision != null)
            {
                OnCollision(m);
            }

            // All the conditions for ignoring this
            if (!enabled)
            {
                return;
            }
            if (state == State.Unpinned)
            {
                return;
            }
            if (collisions > maxCollisions)
            {
                return;
            }
            if (!LayerMaskExtensions.Contains(collisionLayers, m.collision.gameObject.layer))
            {
                return;
            }

            if (LayerMaskExtensions.Contains(groundLayers, m.collision.gameObject.layer))
            {
                if (state == State.GetUp)
                {
                    return;                       // Do not damage if contact with ground layers and in getup state
                }
                if (puppetMaster.muscles[m.muscleIndex].props.group == Muscle.Group.Foot)
                {
                    return;                                                                       // Do not damage if feet in contact with ground layers
                }
            }
            if (masterProps.normalMode == NormalMode.Kinematic && !puppetMaster.isActive && !masterProps.activateOnStaticCollisions && m.collision.gameObject.isStatic)
            {
                return;
            }

            // Activate on Kinematic-Kinematic pair
            if (puppetMaster.muscles[m.muscleIndex].rigidbody.isKinematic && m.collision.collider.attachedRigidbody != null && m.collision.collider.attachedRigidbody.isKinematic)
            {
                if (masterProps.normalMode == NormalMode.Kinematic && puppetMaster.mode == PuppetMaster.Mode.Kinematic)
                {
                    puppetMaster.mode = PuppetMaster.Mode.Active;
                }
            }
            else
            {
                // Get the collision impulse on the muscle
                float cT      = collisionThreshold;
                float impulse = GetImpulse(m, ref cT);

                float minImpulseMlp = PuppetMasterSettings.instance != null ? (1f + PuppetMasterSettings.instance.currentlyActivePuppets * PuppetMasterSettings.instance.activePuppetCollisionThresholdMlp) : 1f;
                float minImpulse    = cT * minImpulseMlp;

                if (impulse <= minImpulse)
                {
                    return;
                }
                collisions++;

                // Try to find out if it collided with another puppet's muscle
                if (m.collision.collider.attachedRigidbody != null)
                {
                    broadcaster = m.collision.collider.attachedRigidbody.GetComponent <MuscleCollisionBroadcaster>();
                    if (broadcaster != null)
                    {
                        if (broadcaster.muscleIndex < broadcaster.puppetMaster.muscles.Length)
                        {
                            // Multiply impulse (if the other muscle has been boosted)
                            impulse *= broadcaster.puppetMaster.muscles[broadcaster.muscleIndex].state.impulseMlp;

                            //float stayF = m.isStay? 0.05f: 0.1f;
                            //broadcaster.puppetMaster.muscles[broadcaster.muscleIndex].offset -= m.collision.impulse * Time.deltaTime * stayF;
                        }
                    }
                }

                // DO not move this up, the impulse value will be wrong.
                // Let other scripts know about the collision (even the ones below collision threshold)
                if (OnCollisionImpulse != null)
                {
                    OnCollisionImpulse(m, impulse);
                }

                // Should we activate the puppet?
                if (Activate(m.collision, impulse))
                {
                    puppetMaster.mode = PuppetMaster.Mode.Active;
                }

                // Unpin the muscle (and other muscles)
                UnPin(m.muscleIndex, impulse);
            }
        }
    void HorizontalCollisions(ref Vector2 moveAmount)
    {
        float directionX = collisions.faceDir;
        float rayLength  = Mathf.Abs(moveAmount.x) + skinWidth;

        //create a layerMask from collisionMask, but exclude OneWayPlatforms on the sides.
        LayerMask adjustedMaskHorizontal = LayerMaskExtensions.RemoveFromMask(collisionMask, oneWayPlatformLayer);

        if (Mathf.Abs(moveAmount.x) < skinWidth)
        {
            //	rayLength = 2*skinWidth;
        }

        for (int i = 0; i < horizontalRayCount; i++)
        {
            //disables the bottom horizontal collision check when moving upwards
            //This was causing the player to 'hit' the slope when jumping, cancelling its velocity
            //if (i == 0 && rawMoveAmount.y > 0) continue;

            Vector2 rayOrigin = (directionX == -1)?raycastOrigins.bottomLeft:raycastOrigins.bottomRight;
            rayOrigin += Vector2.up * (horizontalRaySpacing * i);
            RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.right * directionX, rayLength, adjustedMaskHorizontal);
            //Debug.DrawRay(rayOrigin, Vector2.right * directionX / 2, Color.white);
            Debug.DrawRay(rayOrigin, Vector2.right * directionX * rayLength, Color.red);
            if (hit)
            {
                if (hit.distance == 0)
                {
                    continue;
                }

                float forwardSlopeAngle = Vector2.Angle(hit.normal, Vector2.up);
                //collisions.slopeAngle = forwardSlopeAngle;

                //forward hit from foot has detected slope ahead
                if (i == 0 && forwardSlopeAngle <= maxSlopeAngle)
                {
                    if (collisions.descendingSlope)
                    {
                        Debug.Log("Case 1");
                        collisions.descendingSlope = false;
                        moveAmount = collisions.moveAmountOld;
                    }
                    float distanceToSlopeStart = 0;
                    //slope has changed!
                    if (forwardSlopeAngle != collisions.slopeAngleOld)
                    {
                        Debug.Log("Slope ahead of player changed from " + collisions.slopeAngleOld + " to " + forwardSlopeAngle);
                        distanceToSlopeStart = hit.distance - skinWidth;
                        moveAmount.x        -= distanceToSlopeStart * directionX;
                    }

                    ClimbSlope(ref moveAmount, forwardSlopeAngle, hit.normal);
                    moveAmount.x += distanceToSlopeStart * directionX;
                }

                if (!collisions.climbingSlope || forwardSlopeAngle > maxSlopeAngle)
                {
                    moveAmount.x = (hit.distance - skinWidth) * directionX;
                    rayLength    = hit.distance;

                    if (collisions.climbingSlope)
                    {
                        moveAmount.y = Mathf.Tan(collisions.slopeAngle * Mathf.Deg2Rad) * Mathf.Abs(moveAmount.x);
                    }

                    collisions.left  = directionX == -1;
                    collisions.right = directionX == 1;
                }
            }
        }
    }
示例#28
0
    private void Update()
    {
        if (!kamikazeMode)
        {
            if (currentRockets <= 0)
            {
                kamikazeMode     = true;
                gameObject.layer = LayerMaskExtensions.layermask_to_layer(whatAreOurProjectiles);
                GetComponent <Collider2D>().isTrigger = true;
            }

            curSpd = Mathf.SmoothDamp(curSpd, speed, ref veloc4, 6f);

            if (returningToBaseAlt)
            {
                transform.up = Vector3.MoveTowards(transform.up, retPosition, Random.Range(0.07f, 0.1f));

                if (transform.position.y >= yBaseAltitude)
                {
                    returningToBaseAlt        = false;
                    enemyIsTooCloseEvadeTimer = 0;
                }

                return;
            }

            if (transform.position.y <= waterLevel + 4f && !returningToBaseAlt)
            {
                returningToBaseAlt = true;
                evading            = false;
                retPosition        = new Vector3(transform.up.x * 30f, yBaseAltitude + Random.Range(4f, 6f), transform.position.z);
            }

            if (currentRockets == 0)
            {
                currentRockets = -1;
                Debug.Log("OUT OF ROCKETS!");
            }

            if (evading == true)
            {
                if (Time.time > evadeTimer)
                {
                    evading = false;
                    return;
                }

                if ((target.position - transform.position).magnitude <= aircraftEscapeRange)
                {
                    enemyIsTooCloseEvadeTimer += Time.deltaTime;

                    if (enemyIsTooCloseEvadeTimer >= 5f)
                    {
                        Debug.Log("Too close!");
                        int rand = Random.Range(0, 30) > 20 ? -1 : 1;
                        retPosition        = new Vector3(transform.up.x * Random.Range(14f, 30f) * rand, yBaseAltitude + Random.Range(4f, 14f), transform.position.z);
                        evading            = false;
                        returningToBaseAlt = true;
                    }
                }
                else
                {
                    enemyIsTooCloseEvadeTimer = 0;
                }

                transform.up = Vector3.MoveTowards(transform.up, (evadePos - transform.position).normalized, 0.06f);
                return;
            }

            if (target != null)
            {
                if ((target.position - transform.position).magnitude >= targetCheckRadius)
                {
                    target = null;
                    return;
                }

                bool targetIsVisual = CheckIfLookingAtTarget();

                if (targProps.whatAmI == UnitType.Aircraft)
                {
                    Vector3 dist = (target.position - transform.position + (Vector3)targRb.velocity / 2f).normalized;
                    transform.up = Vector3.MoveTowards(transform.up, dist, 0.04f);

                    if ((target.position - transform.position).magnitude <= aircraftEscapeRange)
                    {
                        evadeVSI = transform.up.x > 0 ? Mathf.CeilToInt(transform.up.x) : Mathf.FloorToInt(transform.up.x);
                        float yAlt = evadeVSI == 1 ? (evadeYAltitude * evadeVSI) * Random.Range(2f, 3f) : (evadeYAltitude * evadeVSI) / Random.Range(8f, 14f);
                        evadePos   = new Vector3(transform.up.x * 100f, yAlt, transform.position.z);
                        evading    = true;
                        evadeTimer = Time.time + evasionLength;
                        return;
                    }
                }
                else // target's a ship yeet
                {
                    Vector3 dist = (target.position - transform.position).normalized;
                    transform.up = Vector3.MoveTowards(transform.up, dist, 0.04f);

                    if ((target.position - transform.position).magnitude <= shipEscapeRange)
                    {
                        evadeVSI = transform.up.x > 0 ? Mathf.CeilToInt(transform.up.x) : Mathf.FloorToInt(transform.up.x);
                        float yAlt = evadeVSI == 1 ? (evadeYAltitude * evadeVSI) / Random.Range(1.4f, 1.6f) : (evadeYAltitude * evadeVSI) / Random.Range(8f, 14f);
                        evadePos   = new Vector3(transform.up.x * 100f, yAlt, transform.position.z);
                        evading    = true;
                        evadeTimer = Time.time + evasionLength;
                        return;
                    }
                }

                if (targetIsVisual)
                {
                    if (Time.time > rocketTimer && currentRockets > 0)
                    {
                        FireRocket();
                    }
                }
            }
            else
            {
                if (FindTarget())
                {
                    targProps = target.GetComponent <ShipHumanoid>();
                    targRb    = target.GetComponent <Rigidbody2D>();
                    return; // looping back to the start since target was found
                }
                else
                {
                    findTargetTimer = Time.time + targetCheckDelay;
                }

                transform.up = Vector3.MoveTowards(transform.up, new Vector2(transform.up.x, 0f), 0.01f);
            }
        }
        else
        {
            if (target)
            {
                if ((target.position - transform.position).magnitude >= targetCheckRadius)
                {
                    target = null;
                    return;
                }

                Vector3 dist = (target.position - transform.position).normalized;
                transform.up = Vector3.MoveTowards(transform.up, dist, 0.04f);

                curSpd = Mathf.SmoothDamp(curSpd, speed * 1.4f, ref veloc4, 7f);
            }

            if (FindTarget())
            {
                targProps = target.GetComponent <ShipHumanoid>();
                targRb    = target.GetComponent <Rigidbody2D>();
                return; // looping back to the start since target was found
            }
            else
            {
                findTargetTimer = Time.time + targetCheckDelay;
            }
        }
    }