Пример #1
0
    void Damage()
    {
        Collider2D[] enemyColList = new Collider2D[5];
        int          enemyNum     = attackTrigger.OverlapCollider(enemyFilter, enemyColList);

        if (enemyNum > 0)
        {
            for (int i = 0; i < enemyNum; i++)
            {
                if (enemyColList[i].GetComponent <Enemy_Dead>().isDead == true)
                {
                    continue;
                }

                Enemy_base enemy_Base = enemyColList[i].GetComponent <Enemy_base>();
                enemy_Base.TakeDamage(1);
                enemy_Base.KnockBack(PlayerControl.facingRight ? Vector3.right : Vector3.left, 100f);
            }
        }

        Collider2D[] atkObjColList = new Collider2D[5];
        int          ObjCount      = attackTrigger.OverlapCollider(canAtkObjFilter, atkObjColList);

        if (ObjCount > 0)
        {
            for (int i = 0; i < ObjCount; i++)
            {
                atkObjColList[i].GetComponent <CanAtkObj>().TakeDamage(1);
            }
        }
    }
Пример #2
0
    protected List <AbstractCreature> getNearbyTargets()
    {
        CircleCollider2D skillRadiusCol = skillRadiusIndicator.AddComponent <CircleCollider2D>();

        skillRadiusCol.isTrigger = true;

        ContactFilter2D cf2d = new ContactFilter2D();

        cf2d.layerMask    = LayerMask.GetMask("Player", "Enemy");
        cf2d.useLayerMask = true;

        Collider2D[] combatantColliders;
        combatantColliders = new Collider2D[100]; //Max of 100 creatures in a combat
        int numOfCombatants = skillRadiusCol.OverlapCollider(cf2d, combatantColliders);
        //Destroy(aoe);
        int i = 0;
        List <AbstractCreature> creaturesInCollision = new List <AbstractCreature>();

        while (combatantColliders[i] != null)
        {
            creaturesInCollision.Add(combatantColliders[i].GetComponent <AbstractCreature>());
            i++;
        }
        return(creaturesInCollision);
    }
Пример #3
0
    bool CheckPlayerPresence()
    {
        ContactFilter2D contactFilter = new ContactFilter2D();

        Collider2D[] colliders = new Collider2D[100];

        int count = zoneDetection.OverlapCollider(contactFilter, colliders);

        for (int i = 0; i < count; i++)
        {
            if (colliders[i].tag == "Player")
            {
                RaycastHit2D hitPlayer = Physics2D.Raycast(transform.position, colliders[i].transform.position - transform.position, Mathf.Infinity, ~(1 << LayerMask.NameToLayer("Monster")));
                Debug.DrawRay(transform.position, colliders[i].transform.position - transform.position);
                if (hitPlayer.collider.tag != "Player")
                {
                    return(false);
                }
                else
                {
                    target = colliders[i].transform;
                    return(true);
                }
            }
        }

        return(false);
    }
Пример #4
0
    //After moving check to see if we are in range of any potential objects we could interact with for GOAP
    public void CreatePostConditions(Dictionary <Condition, object> state)
    {
        GameObject npcPredictor = new GameObject();

        npcPredictor.name = "NPCPREDICTOR";
        npcPredictor.transform.position = predictedPosition;

        ContactFilter2D cf2d = new ContactFilter2D();

        cf2d.layerMask    = LayerMask.GetMask("Items");
        cf2d.useLayerMask = true;

        CircleCollider2D reachedRadius = npcPredictor.AddComponent <CircleCollider2D>();

        reachedRadius.radius    = this.GetComponent <NPC>().reachRadius;
        reachedRadius.isTrigger = true;

        Collider2D[] interactableColliders = new Collider2D[100];
        int          numInteractables      = reachedRadius.OverlapCollider(cf2d, interactableColliders);

        //TODO:

        if (numInteractables != 0)
        {
            for (int i = 0; i < numInteractables; i++)
            {
                float dist = Mathf.Abs(Vector3.Distance(predictedPosition, interactableColliders[i].transform.position));
                postConditions = interactableColliders[i].GetComponent <GOAPInteractable>().ApplyPostConditions(new Dictionary <Condition, object>(), dist);
            }
        }
        Destroy(npcPredictor);
    }
Пример #5
0
    public void InitializeGrid(FlockControl.UnityState us)
    {
        CircleCollider2D cd = GetComponent <CircleCollider2D>();

        gameObject.transform.localScale = new Vector3(CHECK_DISTANCE * us.maxSize, CHECK_DISTANCE * us.maxSize);
        ContactFilter2D cf = new ContactFilter2D();

        cf.useTriggers  = true;
        cf.layerMask    = LayerMask.GetMask("Wall");
        cf.useLayerMask = true;
        Collider2D[] others = new Collider2D[NUM_COLLIDERS];
        grid = new bool[(int)(us.roomWidth / GRID_STEP), (int)(us.roomHeight / GRID_STEP)];


        for (float x = 0; x < us.roomWidth; x += GRID_STEP)
        {
            for (float y = 0; y < us.roomHeight; y += GRID_STEP)
            {
                transform.position = new Vector2(x, y);
                int hit = cd.OverlapCollider(cf, others);
                int gx  = (int)(x / GRID_STEP);
                int gy  = (int)(y / GRID_STEP);
                if (Vector2.SqrMagnitude(new Vector2(x, y) - (Vector2)us.goal.transform.position) < us.goal.transform.localScale.x * us.goal.transform.localScale.x)
                {
                    grid [gx, gy] = true;
                    continue;
                }

                grid [gx, gy] = hit == 0;
            }
        }
        // @Javiar: Foreach node in the grid, look at its eight neighbors
        // Also be sure to include the goal position in the graph you make, even though its neighbors will likely be in the grid
    }
Пример #6
0
    public override IEnumerator DoAction(Dictionary <Condition, object> npcState)
    {
        base.DoAction(npcState);
        ContactFilter2D cf2d = new ContactFilter2D();

        cf2d.layerMask    = LayerMask.GetMask("Items");
        cf2d.useLayerMask = true;

        CircleCollider2D nearbyItemCollider = gameObject.AddComponent <CircleCollider2D>();

        nearbyItemCollider.radius    = closeness;
        nearbyItemCollider.isTrigger = true;

        Collider2D[] interactableColliders = new Collider2D[100];
        int          numInteractables      = nearbyItemCollider.OverlapCollider(cf2d, interactableColliders);

        if (numInteractables != 0)
        {
            for (int i = 0; i < numInteractables; i++)
            {
                if (interactableColliders[i].GetComponent <Wood>() != null)
                {
                    Destroy(interactableColliders[i]);
                    break;
                }
            }
        }

        Destroy(nearbyItemCollider);
        yield return(null);
    }
Пример #7
0
    // Works, spits out how many collision threats it sees (one is own vessel), populates appropriate list if more than one
    int CollisionAvoidancePrepare()
    {
        ContactFilter2D filter = new ContactFilter2D();

        filter.SetLayerMask(TCASLayerMask);
        Collider2D[] contacts = new Collider2D[50];

        int threatCount = visionCollider.OverlapCollider(filter, contacts);

        if (threatCount <= 1)
        {
            return(threatCount);
        }

        collisionThreatList.Clear();
        for (int i = 0; i < threatCount; i++)
        {
            if (contacts[i].gameObject.name != gameObject.name && contacts[i].gameObject.GetComponent <Rigidbody2D>())
            {
                collisonThreatPosition.x = contacts[i].gameObject.transform.position.x;
                collisonThreatPosition.y = contacts[i].gameObject.transform.position.y;
                collisionThreatVelocity  = gameObject.transform.InverseTransformVector(contacts[i].gameObject.GetComponent <Rigidbody2D>().velocity);
                // The position is added twice, just to fill the slot, in later processing it will be upgraded to projected position
                collisionThreatList.Add(new NTools.CollisionThreat(collisonThreatPosition, collisonThreatPosition, collisionThreatVelocity, 0f, 0f));
            }
            else
            {
            }
        }
        return(threatCount);
    }
Пример #8
0
    void Update()
    {
        // Handle Collision
        Collider2D[] colls         = new Collider2D[enemies.Count];
        int          colliderCount = coll.OverlapCollider(new ContactFilter2D().NoFilter(), colls);

        for (int i = 0; i < colliderCount; i++)
        {
            Collider2D enemyCollider = colls[i];
            if (enemies.Contains(enemyCollider.gameObject))
            {
                ColorType type = closestPoint(enemyCollider.gameObject.transform.position);
                if (type == enemyCollider.gameObject.GetComponent <EnemyController>().color)
                {
                    Delete(enemyCollider.gameObject);
                    score.GetComponent <TMP_Text>().text = (int.Parse(score.GetComponent <TMP_Text>().text) + 1).ToString();
                }
                else
                {
                    score.GetComponent <TMP_Text>().text = (int.Parse(score.GetComponent <TMP_Text>().text) - 1).ToString();
                    Delete(enemyCollider.gameObject);
                }
            }
        }
        //Spawn balls
        if (timeTaken > 0.25f)
        {
            timeTaken = 0f;
            System.Random rand = new System.Random();
            SpawnEnemy(float.Parse((360 * rand.NextDouble()).ToString()), (ColorType)Enum.GetValues(typeof(ColorType)).GetValue(rand.Next(0, Enum.GetValues(typeof(ColorType)).Length)));
        }
        timeTaken += Time.deltaTime;
    }
Пример #9
0
    // Update is called once per frame
    void Update()
    {
        bool  grown       = false;
        float growPercent = time.TimeElapsedSecs() / growTime;

        if (growPercent > 1f)
        {
            growPercent = 1f;
            grown       = true;
        }
        float circleSize = growPercent * (scale * canvasUnitsPerAoePoint);

        rt.sizeDelta   = new Vector2(circleSize, circleSize);
        collide.radius = circleSize / 2.05f;   //slightly smaller than image;
        if (grown)
        {
            Destroy(gameObject);
        }

        if (canDamageDial && !hasHitDial)
        {
            Debug.Log("trying to find dial overlap");
            collide.OverlapCollider(filter, collsHit);
            for (int i = 0; i < collsHit.Length; i++)
            { //filter out anything that doesn't get damaged by the field
                Collider2D coll = collsHit[i];
                if (coll != null && coll.gameObject.tag == "Dial")
                {
                    DamageDial(coll.gameObject.GetComponent <Dial>());
                    Debug.Log("found dial overlap!");
                }
            }
        }
    }
Пример #10
0
    public void InitializeGrid(FlockControl.UnityState us)
    {
        graph    = new List <GraphPoint>();
        memoized = new Dictionary <GraphPoint, PathDistance>();

        CircleCollider2D cd = GetComponent <CircleCollider2D>();

        gameObject.transform.localScale = new Vector3(CHECK_DISTANCE * us.maxSize, CHECK_DISTANCE * us.maxSize);

        initCF(us);

        Collider2D[] others = new Collider2D[1];
        grid = new bool[(int)(us.roomWidth), (int)(us.roomHeight)];


        for (int x = 0; x < us.roomWidth; x++)
        {
            for (int y = 0; y < us.roomHeight; y++)
            {
                if (Vector2.SqrMagnitude(new Vector2(x, y) - (Vector2)us.goal.transform.position) < us.goal.transform.localScale.x * us.goal.transform.localScale.x)
                {
                    grid [(int)x, (int)y] = true;
                    continue;
                }

                transform.position = new Vector2(x, y);
                int hit = cd.OverlapCollider(cf, others);
                grid [x, y] = hit == 0;
            }
        }

        initGraph(us.goal.transform.position);
    }
    protected List <AbstractCreature> getNearbyTargets(Vector3 origin)
    {
        GameObject ricochetArrow = new GameObject();

        ricochetArrow.transform.position = origin;
        CircleCollider2D skillRadiusCol = ricochetArrow.AddComponent <CircleCollider2D>();

        skillRadiusCol.isTrigger = true;
        skillRadiusCol.radius    = ricochetRadius;



        Collider2D[] combatantColliders;
        combatantColliders = new Collider2D[100];
        int numOfCombatants = skillRadiusCol.OverlapCollider(cf2d, combatantColliders);

        int i = 0;
        List <AbstractCreature> creaturesInCollision = new List <AbstractCreature>();

        while (combatantColliders[i] != null)
        {
            if (unavailableTargets.Contains(combatantColliders[i].GetComponent <AbstractCreature>()) == false)
            {
                creaturesInCollision.Add(combatantColliders[i].GetComponent <AbstractCreature>());
                unavailableTargets.Add(combatantColliders[i].GetComponent <AbstractCreature>());
            }
            i++;
        }
        Destroy(ricochetArrow);
        return(creaturesInCollision);
    }
Пример #12
0
    private GameObject RandomPowerupTile()
    {
        // Gets all powerups.
        GameObject[] powerups = GameObject.FindGameObjectsWithTag("Powerup");
        // Selects a random powerup.
        GameObject powerup = powerups[Random.Range(0, powerups.Length)];
        // Gets that powerup's collider.
        CircleCollider2D powerupCollider = powerup.GetComponent <CircleCollider2D>();
        // Populates objectsCollidedWith with the colliders colliding with powerupCollider.
        List <Collider2D> objectsCollidedWith = new List <Collider2D>();
        ContactFilter2D   noFilter            = new ContactFilter2D();

        powerupCollider.OverlapCollider(noFilter, objectsCollidedWith);
        // Defines tile as the tile that the powerup is colliding with.
        GameObject tile = null;

        for (int i = 0; i < objectsCollidedWith.Count; i++)
        {
            if (objectsCollidedWith[i].gameObject.tag == "Floor")
            {
                tile = objectsCollidedWith[i].gameObject;
            }
        }
        // Returns that tile.
        return(tile);
    }
Пример #13
0
    private void Update()
    {
        Collider2D[] hits = new Collider2D[20];
        polygonCollider.OverlapCollider(ViewFilter, hits);

        detections = new List <Collider2D>();

        foreach (Collider2D hit in hits)
        {
            if (hit != null)
            {
                detections.Add(hit);
            }
        }

        hits = new Collider2D[20];
        circleCollider.OverlapCollider(ViewFilter, hits);

        foreach (Collider2D hit in hits)
        {
            if (hit != null)
            {
                detections.Add(hit);
            }
        }
    }
Пример #14
0
    public void FindInteractablesInMoveRadius()
    {
        ContactFilter2D cf2d = new ContactFilter2D();

        cf2d.layerMask    = LayerMask.GetMask("Items");
        cf2d.useLayerMask = true;

        CircleCollider2D reachedRadius = gameObject.AddComponent <CircleCollider2D>();

        reachedRadius.radius    = interactableSearchRadius;
        reachedRadius.isTrigger = true;

        Collider2D[] interactableColliders = new Collider2D[100];
        int          numInteractables      = reachedRadius.OverlapCollider(cf2d, interactableColliders);

        if (numInteractables != 0)
        {
            for (int i = 0; i < numInteractables; i++)
            {
                float dist = Mathf.Abs(Vector3.Distance(transform.position, interactableColliders[i].transform.position));
                PredictMove.AddComponent(gameObject, dist, interactableColliders[i].transform.position, moveSpeed, interactableColliders[i].name, i);
                GetComponents <PredictMove>()[i].CreatePostConditions(npcState);
            }
        }
        Destroy(reachedRadius);
    }
Пример #15
0
    private bool IsJointContacting(CircleCollider2D col2D, SpriteRenderer sprite, bool isLeft)
    {
        Collider2D[] results = new Collider2D[10];
        col2D.OverlapCollider(new ContactFilter2D(), results);
        results = results.Where(c => c != null && (c.gameObject.layer == staticPhysicsLayer || c.gameObject.layer == grabbablePhysicsLayer)).ToArray();

        if (results.Length > 0 && results[0] != null)
        {
            if (isLeft)
            {
                leftSprite.sprite = leftSpriteReady;
            }
            else
            {
                rightSprite.sprite = rightSpriteReady;
            }

            return(true);
        }

        if (isLeft)
        {
            leftSprite.sprite = leftSpriteOff;
        }
        else
        {
            rightSprite.sprite = rightSpriteOff;
        }

        return(false);
    }
Пример #16
0
    private void explode()
    {
        ContactFilter2D filter = new ContactFilter2D();

        filter.NoFilter();
        Collider2D[] results = new Collider2D[100];

        explosionCol.OverlapCollider(filter, results);

        foreach (Collider2D col in results)
        {
            if (col == null)
            {
                continue;
            }
            if (col.isTrigger)
            {
                continue;
            }
            if (col.GetComponent <Attributes>() != null)
            {
                col.GetComponent <Attributes>().takeDamage(damage);
            }
            if (col.GetComponent <Prop>() != null)
            {
                col.GetComponent <Prop>().decreaseDurability(damage);
            }
        }
    }
Пример #17
0
    private void Update()
    {
        currentStayTime += Time.deltaTime;
        CircleCollider2D cld = this.GetComponent <CircleCollider2D>();   //获得范围
        //过滤器
        ContactFilter2D filter = new ContactFilter2D
        {
            layerMask    = SoundLayer,
            useTriggers  = true,
            useLayerMask = true
        };
        //用于接收回传
        List <Collider2D> hs = new List <Collider2D>();

        cld.OverlapCollider(filter, hs);        //获取收听者

        foreach (Collider2D c in hs)
        {
            SensoryHearing h = c.gameObject.GetComponent <SensoryHearing>();
            if (h)
            {
                h.Hearing(soundMaker);
            }
        }


        if (currentStayTime >= SoundStayTime)
        {
            SensorySoundSystem.Instance.Recycle(this.gameObject);
            Debug.Log("执行回收");
        }
    }
Пример #18
0
    private DistanceJoint2D LockJoint(Rigidbody2D rigidBody, CircleCollider2D col2D, SpriteRenderer sprite, bool isLeft)
    {
        Collider2D[] results = new Collider2D[10];
        col2D.OverlapCollider(new ContactFilter2D(), results);
        results = results.Where(c => c != null && (c.gameObject.layer == staticPhysicsLayer || c.gameObject.layer == grabbablePhysicsLayer)).ToArray();

        if (results.Length > 0 && results[0] != null)
        {
            if (isLeft)
            {
                leftSprite.sprite = leftSpriteOn;
                leftGrabbed       = true;
            }
            else
            {
                rightSprite.sprite = rightSpriteOn;
                rightGrabbed       = true;
            }

            DistanceJoint2D distJt = rigidBody.gameObject.AddComponent <DistanceJoint2D>();
            distJt.connectedBody         = results[0].attachedRigidbody;
            distJt.connectedAnchor       = results[0].transform.InverseTransformPoint(rigidBody.transform.position);
            distJt.autoConfigureDistance = false;
            distJt.distance = 0.01f;
            AudioManager.instance.PlaySound("stick");
            return(distJt);
        }
        return(null);
    }
Пример #19
0
    public void Agglomerate(int integrity)
    {
        // Debug.Log("AGGLO PRE RETURN");
        if (agglomerationEnabled)
        {
            return;
        }
        // Debug.Log("AGGLO PASS RETURN");
        // AudioController.instance.PlayAggregateOnPlayer();

        tag = "Player";

        this.integrity = integrity;

        Destroy(rb);

        ContactFilter2D filter = new ContactFilter2D();
        int             count  = circleCollider.OverlapCollider(filter, results);

        for (int i = 0; i < count; i++)
        {
            touchingDebrits.Add(results[i].GetComponent <NoColDebrisController>());
        }

        integrity = 0;
        StopCoroutine("Killme");
        agglomerationEnabled = true;
    }
Пример #20
0
    //Returns an array of Collider2Ds of GameObjects within maxRopeLength
    private Collider2D[] getHookables()
    {
        hookableZone.transform.position = gameObject.transform.position;
        ContactFilter2D c = new ContactFilter2D();

        c.SetLayerMask(1 << LayerMask.NameToLayer("Hook"));
        hookableZone.OverlapCollider(c, hookables);
        return(hookables);
    }
    // Start is called before the first frame update
    void Start()
    {
        List <Collider2D> objectsCollidedWith = new List <Collider2D>();
        ContactFilter2D   noFilter            = new ContactFilter2D();

        noFilter.NoFilter();
        for (int colliderI = 0; colliderI < 4; colliderI++)
        {
            objectsCollidedWith.Clear();
            switch (colliderI)
            {
            case 0:
                eastCollider.OverlapCollider(noFilter, objectsCollidedWith);
                break;

            case 1:
                westCollider.OverlapCollider(noFilter, objectsCollidedWith);
                break;

            case 2:
                northCollider.OverlapCollider(noFilter, objectsCollidedWith);
                break;

            case 3:
                southCollider.OverlapCollider(noFilter, objectsCollidedWith);
                break;
            }
            if (objectsCollidedWith.Count > 0)
            {
                for (int i = 0; i < objectsCollidedWith.Count; i++)
                {
                    if (objectsCollidedWith[i].gameObject.tag == "Floor" || objectsCollidedWith[i].gameObject.tag == "Wall")
                    {
                        switch (colliderI)
                        {
                        case 0:
                            eastTile = objectsCollidedWith[i].gameObject;
                            break;

                        case 1:
                            westTile = objectsCollidedWith[i].gameObject;
                            break;

                        case 2:
                            northTile = objectsCollidedWith[i].gameObject;
                            break;

                        case 3:
                            southTile = objectsCollidedWith[i].gameObject;
                            break;
                        }
                        break;
                    }
                }
            }
        }
    }
Пример #22
0
    //Returns an array of Collider2Ds of GameObjects within maxRopeLength
    private Collider2D[] getHookables()
    {
        Collider2D[] hookables = new Collider2D[5]; //make sure to not clump hooks together!
        hookableZone.transform.position = gameObject.transform.position;
        ContactFilter2D c = new ContactFilter2D();

        c.SetLayerMask(1 << LayerMask.NameToLayer("Hook"));
        hookableZone.OverlapCollider(c, hookables);
        return(hookables);
    }
Пример #23
0
    void Update()
    {
        Array.Clear(colliderResults, 0, colliderResults.Length);
        int collisions = collider.OverlapCollider(new ContactFilter2D(), colliderResults);

        if (collisions > 0)
        {
            itemEvent.Invoke();
        }
    }
Пример #24
0
    // Use this for initialization
    void Start()
    {
        wires = new Dictionary <string, Wiring_Script>();
        List <Wiring_Script> adjWires = new List <Wiring_Script>();
        CircleCollider2D     coll     = gameObject.AddComponent <CircleCollider2D>();

        Collider2D[]    collection = new Collider2D[16];
        ContactFilter2D fil        = new ContactFilter2D();

        fil.ClearLayerMask();
        coll.radius    = .6f;
        coll.isTrigger = true;
        coll.OverlapCollider(fil, collection);
        wires.Clear();

        foreach (Collider2D obj in collection)
        {
            if (obj != null && obj.transform.tag == "Wires")
            {
                adjWires.Add(obj.GetComponent <Wiring_Script>());
            }
        }

        foreach (Wiring_Script scr in adjWires)
        {
            Vector3 val = scr.transform.position - transform.position;
            int     x   = (int)Mathf.Round(val.x);
            int     y   = (int)Mathf.Round(val.y);
            switch (x)
            {
            case (-1):
                wires.Add("left", scr);
                break;

            case (1):
                wires.Add("right", scr);
                break;

            default:
                switch (y)
                {
                case (-1):
                    wires.Add("bottom", scr);
                    break;

                case (1):
                    wires.Add("top", scr);
                    break;
                }
                break;
            }
        }

        Destroy(coll);
    }
Пример #25
0
    // Update is called once per frame
    void Update()
    {
        if (isDead)
        {
            deadCooldown -= Time.deltaTime;
            if (deadCooldown <= 0.0f)
            {
                isDead       = false;
                deadCooldown = 1.0f;
            }
        }
        if (pelletCollected)
        {
            pelletCooldown -= Time.deltaTime;
            if (pelletCooldown <= 0.0f)
            {
                pelletCollected = false;
                pelletCooldown  = 0.5f;
            }
        }
        if (lives <= 0)
        {
            // Gameover
            if (globalScript.score > globalScript.e1Score)
            {
                SceneManager.LoadScene("endScreen");
            }
            else
            {
                SceneManager.LoadScene("loseEndScreen");
            }
        }

        // Movement
        //this.GetComponent<Rigidbody2D>().velocity = velocity.normalized * speed;
        GetComponent <Rigidbody2D>().AddForce(velocity.normalized * speed);

        List <Collider2D> objectsCollidedWith = new List <Collider2D>();
        ContactFilter2D   noFilter            = new ContactFilter2D();

        noFilter.NoFilter();
        floorCollider.OverlapCollider(noFilter, objectsCollidedWith);

        if (objectsCollidedWith.Count > 0)
        {
            for (int i = 0; i < objectsCollidedWith.Count; i++)
            {
                if (objectsCollidedWith[i].gameObject.tag == "Floor")
                {
                    currentFloorTile = objectsCollidedWith[i].gameObject;
                }
            }
        }
    }
Пример #26
0
    void FixedUpdate()
    {
        //if (Time.frameCount / 30 == 0) //проверку коллизий можно делать не каждый фрейм в некоторых играх

        //коллизия: Шар - Блок
        int s = cc.OverlapCollider(cfBlock, crBlock);

        if (s > 0)
        {
            Vector3 _speed = Speed;

            for (int i = 0; i < s; i++)
            {
                if ((tr.position.x > crBlock[i].bounds.max.x) || (tr.position.x < crBlock[i].bounds.min.x))
                {
                    _speed.x = -Speed.x;
                }
                if ((tr.position.y > crBlock[i].bounds.max.y) || (tr.position.y < crBlock[i].bounds.min.y))
                {
                    _speed.y = -Speed.y;
                }

                crBlock[i].GetComponent <Block>().BallHitsBlock();
                //Debug.Log(crBlock[i].bounds.size.x);
            }
            Speed = _speed;
        }

        tr.position += Speed;

        //коллизия со стенками
        if ((MyGameManager._inst.GameArea.xMin) > tr.position.x - rad)
        {
            tr.position = new Vector3(MyGameManager._inst.GameArea.xMin + rad, tr.position.y, 0);
            Speed.x    *= -1;
        }
        if ((MyGameManager._inst.GameArea.xMax) < tr.position.x + rad)
        {
            tr.position = new Vector3(MyGameManager._inst.GameArea.xMax - rad, tr.position.y, 0);
            Speed.x    *= -1;
        }
        if ((MyGameManager._inst.GameArea.yMax) < tr.position.y + rad)
        {
            tr.position = new Vector3(tr.position.x, MyGameManager._inst.GameArea.yMax - rad, 0);
            Speed.y    *= -1;
        }
        if ((MyGameManager._inst.GameArea.yMin) > tr.position.y - rad)
        {
            //Destroy(this.gameObject);
            tr.position = new Vector3(tr.position.x, MyGameManager._inst.GameArea.yMin + rad, 0);
            Speed.y    *= -1;
        }
    }
Пример #27
0
    private bool IsAboveGoodContainer()
    {
        ContactFilter2D filter = new ContactFilter2D();

        filter.layerMask   = gameObject.layer;
        filter.useTriggers = true;
        List <Collider2D> results = new List <Collider2D>();

        _circleCollider2D.OverlapCollider(filter, results);

        foreach (Collider2D collider in results)
        {
            Conteiner container = collider.GetComponent <Conteiner>();
            if (container != null)
            {
                if (_objectColor.HasFlag(container.ObjectColor))
                {
                    Conteiner.OnColorMatch?.Invoke(container.ObjectColor);
                    if (tapParticles)
                    {
                        tapParticles.Play();
                    }
                    _unmatched = false;
                    return(true);
                }
                else
                {
                    _unmatched = true;
                }
            }
            SecondaryObjectiveSocket socket = collider.GetComponent <SecondaryObjectiveSocket>();
            if (socket != null)
            {
                if (_objectColor.HasFlag(socket.SocketColor) && !socket.IsFull)
                {
                    socket.InstallGem(this);
                    if (tapParticles)
                    {
                        tapParticles.Play();
                    }
                    _unmatched = false;
                    return(true);
                }
                else
                {
                    _unmatched = true;
                }
            }
        }
        return(false);
    }
    private float EnemyOverlapDistance()
    {
        // set up contact filter and results array
        ContactFilter2D colliderFilter = new ContactFilter2D();

        colliderFilter.SetLayerMask(LayerMask.GetMask("Monster"));

        Collider2D[] results = new Collider2D[5];

        // find collider overlap
        int numberOfContacts = _collider.OverlapCollider(colliderFilter, results);

        return(numberOfContacts > 0 ? ReturnClosestEnemyDistance(results, numberOfContacts) : -1);
    }
Пример #29
0
    /*
     * void OnTriggerEnter2D(Collider2D tempCollider)
     * {
     *  if (tempCollider.gameObject.tag != ignoreTagName)
     *  {
     *      collisionTargerNum++;
     *  }
     * }
     *
     * void OnTriggerExit2D(Collider2D tempCollider)
     * {
     *  if (tempCollider.gameObject.tag != ignoreTagName)
     *  {
     *      collisionTargerNum--;
     *  }
     * }
     */
    public bool CheckCollided()
    {
        int number = circleCollider.OverlapCollider(GameManerge.Get_obj.canshu, colliders);

        for (int i = 0; i < number; i++)
        {
            if (colliders[i].tag == "DiXing")
            {
                return(true);
            }
        }
        return(false);
        //return ( circleCollider.OverlapCollider(GameManerge.Get_obj.canshu,new Collider2D[5])- collisionTargerNum > 0) ? true : false;
    }
Пример #30
0
    void DamageArea()
    {
        List <Collider2D> overlapped = new List <Collider2D>();
        var filter = new ContactFilter2D();

        filter.useLayerMask = true;
        filter.SetLayerMask(LayerMask.GetMask("Enemy"));

        int count = damageCollider.OverlapCollider(filter, overlapped);

        foreach (var o in overlapped)
        {
            Destroy(o.gameObject);
        }
    }