/// <summary>
    /// Checks collisions in y axis.
    /// </summary>
    /// <param name="moveAmount"></param>
    void VerticalCollisions(ref Vector2 moveAmount)
    {
        float directionY  = Mathf.Sign(moveAmount.y);
        float directionX  = Mathf.Sign(moveAmount.x);
        float rayDistance = Mathf.Abs(moveAmount.y) + skinWidth;

        // Box cast for collisions
        RaycastHit2D hit = Physics2D.BoxCast(boxCollider.bounds.center, boxCollider.bounds.size, 0f, Vector2.up * directionY, rayDistance, collisionMask);

        if (hit)
        {
            ColliderDistance2D colliderDistance = hit.collider.Distance(boxCollider);
            if (colliderDistance.isOverlapped && colliderDistance.isValid)
            {
                moveAmount.y = (colliderDistance.pointA - colliderDistance.pointB).y;
            }
            else
            {
                moveAmount.y = (hit.distance - skinWidth) * directionY;
            }

            contacts.above = directionY == 1;
            contacts.below = directionY == -1;

            if (contacts.below)
            {
                contacts.inAir = false;
            }
        }
    }
Example #2
0
    public void TryCorrectEnemyPosition()
    {
        //create an array that overlapping colliders can be sent to
        Collider2D[] stageGrenadeColliders = new Collider2D[10];

        //do an overlap collider check with the grenade's circle collider using the contact filter and outputting results to the previously declared array
        GetComponent <BoxCollider2D>().OverlapCollider(filter, stageGrenadeColliders);

        //for each collider that passes through the contact filter in the overlap collider check
        foreach (Collider2D incomingCollider in stageGrenadeColliders)
        {
            //if the collider is not null
            if (incomingCollider != null && !incomingCollider.gameObject.GetComponentInParent <ToolBehaviourGeyser>())
            {
                //use the ColliderDistance2D to get information about the collider overlap, this compares the grenade circle collider to stage collider which comes in through incoming collider
                stageCheck = GetComponent <BoxCollider2D>().Distance(incomingCollider);

                //if the check is definitely overlapping and it is valid
                if (stageCheck.isOverlapped && stageCheck.isValid)
                {
                    //Debug.DrawLine(stageCheck.pointB, stageCheck.pointA, Color.cyan);//draw a line to show the two points created THIS IS FOR DEBUGGING

                    //create the correction vector, this is done by taking the normal (direction) of the stage check and the distance of the stage check and multiplying them together
                    Vector2 correction = (stageCheck.normal * stageCheck.distance);
                    //adjust the grenade rigidbody to be properly corrected outside of the stage collider
                    GetComponent <Rigidbody2D>().position = GetComponent <Rigidbody2D>().position + correction;
                    //adjust the transform to the new rigidbody position for accuracy
                    transform.position = GetComponent <Rigidbody2D>().position;
                }
            }
        }
    }
Example #3
0
    private void setupDistCache()
    {
        for (int i = 0; i < birdControls.Length; i++)
        {
            for (int j = i + 1; j < birdControls.Length; j++)
            {
                BirdControl        b1    = birdControls [i];
                BirdControl        b2    = birdControls [j];
                ColliderDistance2D cd    = b1.GetComponent <Collider2D>().Distance(b2.GetComponent <Collider2D>());
                Vector2            delta = (cd.pointB - cd.pointA);
                b1.SetDistance(b2, delta);
                b2.SetDistance(b1, -1 * delta);
            }
        }

        for (int i = 0; i < birdControls.Length; i++)
        {
            for (int j = 0; j < walls.Length; j++)
            {
                BirdControl        b1    = birdControls [i];
                GameObject         wall  = walls [j];
                ColliderDistance2D cd    = b1.GetComponent <Collider2D>().Distance(wall.GetComponent <Collider2D>());
                Vector2            delta = (cd.pointB - cd.pointA);
                b1.SetWallDist(j, delta);
            }
        }
    }
Example #4
0
    private void CheckHit(RaycastHit2D _hit)
    {
        // Extract from collider if overlap
        ColliderDistance2D _distance = collider.Distance(_hit.collider);

        if (_distance.isOverlapped)
        {
            Vector2 _movement = _distance.pointA - _distance.pointB;
            _movement          = _movement.normalized * (_movement.magnitude - Physics2D.defaultContactOffset);
            transform.position = (Vector2)transform.position - _movement;
            rigidbody.MovePosition(rigidbody.position - _movement);
        }

        if (_hit.collider.gameObject.HasTag("Player") && doHit)
        {
            _hit.collider.GetComponent <MyPlayercontroller>().Kill(originalVelocity);
            DestroyProjectile();
            return;
        }

        if (_hit.collider.gameObject.HasTag("Projectile"))
        {
            _hit.collider.GetComponent <Projectile>().Bounce(originalVelocity);
        }

        bounceCount--;

        if ((bounceCount < 1) || _hit.collider.gameObject.HasTag("Spike"))
        {
            DestroyProjectile();
            return;
        }

        Bounce(_hit.normal);
    }
Example #5
0
    void OnTriggerEnter2D(Collider2D col)
    {
        if (col.gameObject.tag == "BorderLeft")
        {
            coldist = this.gameObject.GetComponent <Collider2D>().Distance(col);
            this.transform.position -= new Vector3((float)(coldist.distance), 0);
            velocityL  = Vector3.zero;
            hitBorderL = true;
        }

        if (col.gameObject.tag == "BorderRight")
        {
            coldist = this.gameObject.GetComponent <Collider2D>().Distance(col);
            this.transform.position += new Vector3((float)(coldist.distance), 0);
            velocityR  = Vector3.zero;
            hitBorderR = true;
        }

        if (col.gameObject.tag == "BorderUp")
        {
            coldist = this.gameObject.GetComponent <Collider2D>().Distance(col);
            this.transform.position += new Vector3(0, (float)(coldist.distance));
            velocityU  = Vector3.zero;
            hitBorderU = true;
        }

        if (col.gameObject.tag == "BorderDown")
        {
            coldist = this.gameObject.GetComponent <Collider2D>().Distance(col);
            this.transform.position -= new Vector3(0, (float)(coldist.distance));
            velocityD  = Vector3.zero;
            hitBorderD = true;
        }
    }
Example #6
0
    Vector2 findPointToFace(float checkRadius)
    {
        RaycastHit2D[]     hits                     = Physics2D.CircleCastAll((Vector2)grabCollider.transform.position, checkRadius, new Vector2(), 0, layers);
        List <Transform>   transforms               = new List <Transform>();
        float              shortestDistance         = 100000;
        ColliderDistance2D shortestColliderDistance = new ColliderDistance2D();
        GameObject         nearestObject            = null;

        foreach (RaycastHit2D hit in hits)
        {
            if (hit.transform != transform && transforms.Contains(hit.transform) == false)
            {
                ColliderDistance2D colliderDistance = hit.collider.Distance(grabCollider);
                float distance = colliderDistance.distance;

                if (distance < shortestDistance)
                {
                    shortestDistance         = distance;
                    nearestObject            = hit.collider.gameObject;
                    shortestColliderDistance = colliderDistance;
                }
            }
        }

        if (shortestColliderDistance.pointB != null)
        {
            Debug.DrawLine(shortestColliderDistance.pointA, shortestColliderDistance.pointB, Color.green);
            return(shortestColliderDistance.pointA);
        }
        else
        {
            return(nullPoint);
        }
    }
Example #7
0
    //FixedUpdate is called at a fixed interval and is independent of frame rate. Put physics code here.
    void FixedUpdate()
    {
        //Store the current horizontal input in the float moveHorizontal.
        float moveHorizontal = Input.GetAxis("Horizontal");

        //Store the current vertical input in the float moveVertical.
        float moveVertical = Input.GetAxis("Vertical");

        //Use the two store floats to create a new Vector2 variable movement.
        Vector2 movement = new Vector2(moveHorizontal, moveVertical);

        velocity.x = Mathf.MoveTowards(velocity.x, speed * movement.x, Time.deltaTime);
        velocity.y = Mathf.MoveTowards(velocity.y, speed * movement.y, Time.deltaTime);

        transform.Translate(velocity * Time.deltaTime);

        Collider2D[] hits = Physics2D.OverlapBoxAll(transform.position, boxCollider.size, 0);

        foreach (Collider2D hit in hits)
        {
            if (hit != boxCollider)
            {
                ColliderDistance2D distance2D = hit.Distance(boxCollider);

                if (distance2D.isOverlapped)
                {
                    transform.Translate(distance2D.pointA - distance2D.pointB);
                }
            }
        }
    }
Example #8
0
    public static Vector2 GetClosestPointOnPlanet(Collider2D collider, float offset = 0f)
    {
        ValidateCollider(ref collider);
        bool wasOn = collider.enabled;

        collider.enabled = true;
        var                planets              = GameObject.FindGameObjectsWithTag("Planet");
        float              closestDistance      = float.MaxValue;
        GameObject         closestPlanetGO      = null;
        ColliderDistance2D closestCollisionData = default;

        foreach (var p in planets)
        {
            Collider2D planetCollider = p.GetComponent <Collider2D>();
            var        colliderDist   = planetCollider.Distance(collider);
            float      dist           = colliderDist.distance;
            if (dist < closestDistance)
            {
                closestPlanetGO      = p;
                closestDistance      = dist;
                closestCollisionData = colliderDist;
            }
        }
        collider.enabled = wasOn;


        if (offset == 0f)
        {
            return(closestCollisionData.pointA);
        }
        else
        {
            return(((closestCollisionData.pointB - closestCollisionData.pointA).normalized * offset) + closestCollisionData.pointA);
        }
    }
Example #9
0
    /// <summary>
    ///  Unity API. Raises the trigger stay 2d event.
    /// </summary>
    /// <param name="coll">Collider information.</param>
//	void OnTriggerStay2D(Collider2D coll)
//	{
//		return;
//
//		// OnTriggerStay2D is used instead of OnTriggerEnter2D bc the latter misses the complete detection
//		if (coll.gameObject.CompareTag ("Cargo"))
//		{
//			Cargo _cargoScript = coll.gameObject.GetComponent<Cargo> ();
//			isCargoInside = _cargoScript.IsCargoInsideGoal ();
//		}
//		else
//		{
//			return;
//		}
//
//		// Testing other ways of determining the distance
//		Collider2D cargoCollider = coll.gameObject.GetComponent<Collider2D> ();
//		ColliderDistance2D distance = goalCollider.Distance (cargoCollider);
//		Debug.Log ("Distance: " + distance.distance);
//
//		Debug.Log ("isCargoInside: " + isCargoInside);
//	}

    /// <summary>
    /// Detects if the cargo is inside the goal.
    /// </summary>
    void DetectCargo()
    {
//		Debug.Log ("We'll detect the cargo");

        // Deprecated, Unity has a built in method that is more efficient and
        // provides useful information
//		isCargoInside = cargoScript.IsCargoInsideGoal ();
//		Debug.Log ("isCargoInside: " + isCargoInside);

        // Ensuring the cargo is completely inside the goal, -1f bc the cargo is 1f in all axis in scale
        ColliderDistance2D _distance = goalCollider.Distance(cargoCollider);

//		Debug.Log ("_distance.distance: " + _distance.distance);

        if (_distance.distance < -cargoScript.goalThreshold)
        {
//			Debug.Log ("Cargo is inside the goal");
            gameManager.Invoke("WereCargoesDelivered", cargoGoalDelay);
        }
        else if (_distance.distance >= -cargoScript.goalThreshold)
        {
//			Debug.Log ("Cargo not completely inside goal");
            gameManager.CancelInvoke("WereCargoesDelivered");
            gameManager.LevelNotEnded();
        }
    }
Example #10
0
    private void OnCollisionEnter2D(Collision2D other)
    {
        // TODO: more consistent raycast logic needed
        ColliderDistance2D colliderDistance = other.collider.Distance(boxCollider);

        // if collision causes an overlap, move the object so that it's no longer overlapping

        if (colliderDistance.isOverlapped)
        {
            transform.Translate(colliderDistance.pointA - colliderDistance.pointB);
        }

        if (other.collider.tag == "Collideable")
        {
            if (colliderDistance.normal == Vector2.up)
            {
                this.grounded = true;
            }
        }

        if (other.collider.tag == "Player")
        {
            if (colliderDistance.normal == Vector2.up)
            {
                rb.velocity = Vector2.up * 2.5f;
            }
            if (colliderDistance.normal == Vector2.down)
            {
                TakeDamage(1, other.gameObject);
            }
        }
    }
Example #11
0
    // Update is called once per frame
    protected override void FixedUpdate()
    {
        base.FixedUpdate();
        GameObject playerObj = GameObject.FindGameObjectWithTag("Player");

        if (playerObj)
        {
            Collider2D playerCollider = playerObj.GetComponent <BoxCollider2D>();
            float      playerDistance = Vector2.Distance(this.transform.position, playerObj.transform.position);

            //enable collider to calculate distance, then restore to prev state
            bool enabledState = this.attackMeleeCollider.enabled;
            this.attackMeleeCollider.enabled = true;
            ColliderDistance2D playerColliderDistance = Physics2D.Distance(this.attackMeleeCollider, playerCollider);
            this.attackMeleeCollider.enabled = enabledState;

            if (playerColliderDistance.distance <= 0)
            {
                this.AttackMelee();
            }
            else if (playerDistance < huntRadius)
            {
                this.Move((playerObj.transform.position - this.transform.position).normalized);
            }
            else
            {
                this.Move(Vector3.zero);
            }
        }

        if (this.attackCooldownRemaining > 0)
        {
            this.attackCooldownRemaining -= Time.deltaTime;
        }
    }
    protected void WalkIntoDirection(int layerMask, Vector3 direction)
    {
        Vector2 newVelocity         = (Vector2)direction * (speedFactor * this.soldierConfig.maxSpeed);
        int     lookForwardDistance = 5;

        RaycastHit2D[] hits = Physics2D.RaycastAll(new Vector2(transform.position.x, -1), (Vector2)direction, lookForwardDistance, layerMask);
        if (hits.Length > 1)
        {
            ColliderDistance2D colliderDistance = Physics2D.Distance(hits[0].collider, hits[1].collider);
            float offsetThreshold = 0.5f;
            if (colliderDistance.distance < offsetThreshold)
            {
                newVelocity = hits[1].rigidbody.velocity;
            }
        }

        if (newVelocity.magnitude < 0.1f)
        {
            StopWalking();
        }
        else
        {
            this.body.angularVelocity = 0;
            body.velocity             = Vector2.Lerp(body.velocity, newVelocity, 0.1f);
        }
    }
Example #13
0
    void DetectGround()
    {
        is_grounded = false;

        if (ground_check != null)
        {
            Collider2D[] hits = Physics2D.OverlapBoxAll(ground_check.transform.position, ground_check.size, 0, what_is_ground);

            foreach (Collider2D hit in hits)
            {
                if (hit.CompareTag("Player"))
                {
                    continue;
                }

                is_grounded = true;
                ColliderDistance2D colliderDistance = hit.Distance(box_collider);

                if (colliderDistance.isOverlapped)
                {
                    transform.Translate(colliderDistance.pointA - colliderDistance.pointB);
                }
            }
            //is_grounded = Physics2D.OverlapBox(ground_check.transform.position, ground_check.size, 0f, what_is_ground);
        }
    }
Example #14
0
    void HandleCollision()
    {
        isGrounded = false;

        // Retrieve all colliders we have intersected after velocity has been applied.
        Collider2D[] hits = Physics2D.OverlapBoxAll(transform.position, boxCollider.size, 0);

        foreach (Collider2D hit in hits)
        {
            // Ignore our own collider.
            if (hit == boxCollider)
            {
                continue;
            }

            ColliderDistance2D colliderDistance = hit.Distance(boxCollider);

            // Ensure that we are still overlapping this collider.
            // The overlap may no longer exist due to another intersected collider pushing us out of this one.
            if (colliderDistance.isOverlapped)
            {
                transform.Translate(colliderDistance.pointA - colliderDistance.pointB);

                // If we intersect an object beneath us, set Grounded to true.
                if (Vector2.Angle(colliderDistance.normal, Vector2.up) < 90 && velocity.y < 0)
                {
                    isGrounded = true;
                }
            }
        }
    }
Example #15
0
    void Update()
    {
        Collider2D[] hits = Physics2D.OverlapBoxAll(transform.position, boxCollider.size, 0); /*burada karakter ile 'collide' olan nesneleri toplayan bir liste yaptık
                                                                                               * üç argüman var sırasıyla point,size,angle
                                                                                               * point = collider veya hitbox'un ortası
                                                                                               * size = collider boyutu, bizimkisi karakteri saran bir boxCollider componenti olacaktır.
                                                                                               * angle açıdır, colliderı döndürmek için kullanılabilir.
                                                                                               * SİZE,POİNT VE ANGLE İLE BİR COLLİDER OLUŞTURULUR, OverlapBoxAll İSE BU COLLİDER A ÇARPAN BAŞKA COLLİDERLARI YAZDIRIR.. BURASI ÇOKOMELLİ..:)
                                                                                               * bu listenin ilk elemanları => ground , character(boxcollider) dir. başka bir cisme çarpınca yenisi eklenir.
                                                                                               */



        foreach (Collider2D hit in hits)                          //listedeki elemanları tarıyor...
        {
            if (hit == boxCollider)                               /*buradaki boxColllider üstte tanımladığımız boxcollider2d dir. Yani karakterin kendi collideridir.
                                                                   * Karakter aslinda her zaman kendiyle "collide" oluyor, bunu engellemek için bunu yazdık.*/
            {
                continue;
            }

            ColliderDistance2D colliderDistance = hit.Distance(boxCollider); //distance = çarpılan collider (hit) ile argüman olarak verilen collider (boxCollider yani karakterin collideri) arasındaki mesafeyi belirtir.

            if (colliderDistance.isOverlapped)                               //isOverlapped = True ise colliderin içine girmiş (bir nevi noclip olmuş) demektir.
            {
                transform.Translate(colliderDistance.pointA - colliderDistance.pointB);
            }
        }
    }
Example #16
0
    private void UpdateMovement()
    {
        switch (cameraMode)
        {
        case (CameraMode.Mobile):
            Vector2 trackedPosition = Vector2.zero;
            Vector2 lookDir         = Vector2.zero;
            Vector2 velocityDir     = Vector2.zero;
            if (trackedPlayer.timeOfDeath + 3 < Time.time && gameManager.scoreboard.Single(p => p.player == trackedPlayer).lives == 0)
            {
                trackedPosition = players[spectatedPlayerIndex].transform.position;
            }
            else
            {
                trackedPosition = trackedPlayer.transform.position;
                lookDir         = trackedPlayer.lookDirection;
                //velocityDir = Vector2.ClampMagnitude(trackedPlayer.velocity * 0.1f, 3f);
            }

            Vector2 softLockMoveDir = (trackedPosition - softLockPosition);
            softLockPosition += softLockMoveDir.normalized * Mathf.Clamp(softLockMoveDir.magnitude - softLockMinDistance, 0, Mathf.Infinity);

            trackBox.transform.position = softLockPosition + lookDir + velocityDir;

            // Find the closest position for the camera within the camera bounds
            Vector2 closestPoint    = Vector2.zero;
            float   closestDistance = Mathf.Infinity;

            foreach (BoxCollider2D cameraBounds in allCameraBounds)
            {
                if (cameraBounds.OverlapPoint(trackBox.transform.position) == true)
                {
                    closestPoint    = trackBox.transform.position;
                    closestDistance = 0;
                    break;
                }

                ColliderDistance2D colDist2D = Physics2D.Distance(cameraBounds, trackBox);
                float thisDistance           = Vector2.Distance(trackBox.transform.position, colDist2D.pointA);
                if (thisDistance < closestDistance)
                {
                    closestDistance = thisDistance;
                    closestPoint    = colDist2D.pointA;
                }
            }

            desiredPosition = closestPoint;

            cameraPosition = Vector3.Lerp(cameraPosition, desiredPosition, 20f * Time.deltaTime);

            break;

        case (CameraMode.Static):
            // Be static?
            break;
        }
        // Move camera
        transform.position = new Vector3(Mathf.Round(cameraPosition.x * 12) / 12, Mathf.Round(cameraPosition.y * 12) / 12, -1);
    }
    private void Update()
    {
        float acceleration = grounded ? walkAcceleration : airAcceleration;
        float deceleration = grounded ? groundDeceleration : 0;

        velocity.y += Physics2D.gravity.y * Time.deltaTime;

        //Debug.Log(Time.deltaTime);
        //Debug.Log(velocity.y);
        //Debug.Log(grounded);


        if (grounded)
        {
            velocity.y = 0;

            if (Input.GetButtonDown("Jump"))
            {
                velocity.y = Mathf.Sqrt(2 * jumpHeight * Mathf.Abs(Physics2D.gravity.y));
            }
        }

        float moveInput = Input.GetAxisRaw("Horizontal");

        if (moveInput != 0)
        {
            velocity.x = Mathf.MoveTowards(velocity.x, speed * moveInput, acceleration * Time.deltaTime);
            transform.Translate(velocity * Time.deltaTime);
        }

        else
        {
            velocity.x = Mathf.MoveTowards(velocity.x, 0, deceleration * Time.deltaTime);
        }

        Collider2D[] hits = Physics2D.OverlapBoxAll(transform.position, boxCollider.size, 0);

        grounded = false;

        for (int i = 0; i < hits.Length; i++)
        {
            if (hits[i] == boxCollider)
            {
                continue;
            }

            ColliderDistance2D colliderDistance = hits[i].Distance(boxCollider);

            if (Vector2.Angle(colliderDistance.normal, Vector2.up) < 90 && velocity.y < 0)
            {
                grounded = true;
            }

            if (colliderDistance.isOverlapped)
            {
                transform.Translate(colliderDistance.pointA - colliderDistance.pointB);
            }
        }
    }
Example #18
0
    private void handleWallCollision(Collider2D other)
    {
        ColliderDistance2D dist = gameObject.GetComponent <Collider2D>().Distance(other);

        transform.position += (Vector3)dist.normal * dist.distance;
        velocity            = getResultantVelocity(transform.position, dist.pointB, mass, Mathf.Infinity, velocity, Vector2.zero);
        statsControl.AddWallCollision(number);
    }
        private static bool CanInteract(GameObject interactable, Interactor interactor)
        {
            Collider2D         interactableCollider = interactable.GetComponent <Collider2D>();
            Collider2D         interactorCollider   = interactor.GetComponent <Collider2D>();
            ColliderDistance2D colliderDistance     = interactableCollider.Distance(interactorCollider);

            return(colliderDistance.isOverlapped || colliderDistance.distance == 0);
        }
Example #20
0
    private Vector2 GetClosetPositionOutside(Vector2 shieldCenter)
    {
        shieldCollider.geometryType = CompositeCollider2D.GeometryType.Outlines;
        ColliderDistance2D distance = unitCollider.Distance(shieldCollider);

        shieldCollider.geometryType = CompositeCollider2D.GeometryType.Polygons;
        return(distance.pointB + (distance.pointB - shieldCenter).normalized * 1.5f);
    }
    private void OnTriggerStay2D(Collider2D other)
    {
        touching = true;
        ColliderDistance2D dist = _repelTrigger.Distance(other);

        _rb.AddForce((dist.distance * repelForce - Vector2.Dot(dist.normal, _rb.velocity) * stickiness) * dist.normal);
        groundedNormal = -dist.normal;
    }
    virtual public bool IsConnectedToOther()
    {
        // check if close to other player and they are on a pointer
        CircleCollider2D   otherCollider = otherPlayer.GetComponent <CircleCollider2D>();
        ColliderDistance2D distance      = rigidbody.Distance(otherCollider);

        return(distance.distance < otherCollider.radius);
    }
        private static bool CanBeCollected(GameObject collectable, Collector collector)
        {
            Collider2D         collectableCollider = collectable.GetComponent <Collider2D>();
            Collider2D         collectorCollider   = collector.GetComponent <Collider2D>();
            ColliderDistance2D colliderDistance    = collectableCollider.Distance(collectorCollider);

            return(colliderDistance.isOverlapped || colliderDistance.distance == 0);
        }
Example #24
0
        // CheckGround is responsible for checking if the player has reached the ground, and calling the Land action.
        private void CheckGround()
        {
            ColliderDistance2D attractableBodyToAttractiveBodyGroundDistance = this.attractableBodyCollider.Distance(this.ClosestAttractiveBody.ground);

            if (attractableBodyToAttractiveBodyGroundDistance.distance < groundedDistance)
            {
                StartCoroutine(this.PlayerMovingState.Land());
            }
        }
Example #25
0
    void FixedUpdate()
    {
        float avg    = 0;
        int   avgCnt = 0;
        float dirtyShortestDistance = Mathf.Infinity;
        float dirtyShortestAngle    = 90;

        string angles = "";

        others.RemoveAll(o => o == null);
        others.ForEach(o =>
        {
            ColliderDistance2D distance2D = o.Distance(collider);
            float angle = Mathf.Rad2Deg * Mathf.Atan2(distance2D.normal.y, distance2D.normal.x);
            Debug.DrawLine(transform.position, transform.position + new Vector3(distance2D.normal.x, distance2D.normal.y, 0), Color.black);
            if (angle < 0)
            {
                angle += 360;
            }
            if (angle > 180)
            {
                angle -= 360;
            }
            angles += "/" + angle;
            if (Mathf.Abs(angle - 90) <= maxAngle)
            {
                avg += (angle - 90);
                avgCnt++;

                if (dirtyShortestDistance > distance2D.distance)
                {
                    dirtyShortestAngle    = angle - 90;
                    dirtyShortestDistance = distance2D.distance;
                }
            }
        });

        if (avgCnt == 0)
        {
            //Debug.Log(transform.parent.gameObject.name + " no normals: ");
            transform.parent.rotation = Quaternion.Euler(0, 0, 0);
            return;
        }
        // Debug.Log(angles);
        if (avgCnt > 0)
        {
            avg = avg / avgCnt;
        }

        transform.parent.rotation = Quaternion.Euler(0, 0, dirtyShortestAngle /* avg */);
        if (playerMovement != null)
        {
            playerMovement.Normal = Quaternion.Euler(0, 0, /* avg */ dirtyShortestAngle + 90) * Vector3.right; // FIXME
        }
        //Debug.Log(transform.parent.gameObject.name + " normals: " + avg + "/" + avgCnt);
    }
Example #26
0
    private float scale = 1f;     // default

    // Start is called before the first frame update
    void Start()
    {
        if (saveRun)
        {
            Time.captureFramerate = framerate;
        }

        LoadSettings();
        scale = Scale();

        Debug.Log(num);

        Random.InitState(seed);

        for (int i = 0; i < num; i++)
        {
            int shapeindex;
            Debug.Log(togglePolygons);
            if (togglePolygons)
            {
                shapeindex = (int)Random.Range(0, shapes.Length);
            }
            else
            {
                shapeindex = 0;         //index of circle only
            }
            GameObject  aShape = Instantiate(shapes[shapeindex], Random.insideUnitCircle * 8, Quaternion.identity);
            Rigidbody2D rb     = aShape.GetComponent <Rigidbody2D>();
            Collider2D  col    = aShape.GetComponent <Collider2D>();
            aShape.GetComponent <Transform>().localScale += new Vector3(1f, 1f, 0) * Scale();


            Collider2D[]    results = new Collider2D[num];
            ContactFilter2D filter  = new ContactFilter2D();

            int numOverlaps = rb.OverlapCollider(filter.NoFilter(), results);
            Debug.Log(numOverlaps);

            if (0 != rb.OverlapCollider(filter.NoFilter(), results))
            {
                for (int j = 0; j < numOverlaps; j++)
                {
                    ColliderDistance2D overlap = col.Distance(results[j]);
                    aShape.GetComponent <Transform>().Translate((Vector3)overlap.normal * overlap.distance, Space.World);
                    Debug.Log(aShape.GetComponent <Transform>().position);
                }
                rb = aShape.GetComponent <Rigidbody2D>();
            }

            // aShape.GetComponent<SpriteRenderer>().color = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f); //randomizes color on each shape
            // aShape.GetComponent<SpriteRenderer>().color = blue;
            rb.velocity    = (Vector2)Random.onUnitSphere * Random.Range(10 * (1 - variability), 10 * (1 + variability));
            rb.drag        = friction;
            rb.angularDrag = angularDrag;
        }
    }
Example #27
0
    public void GO(Vector2 StartingLoc, Collider2D map)
    {
        speed  = Speed;
        OnLand = false;

        transform.position = StartingLoc;
        ColliderDistance2D distance = gameObject.GetComponent <Collider2D>().Distance(map);

        transform.rotation = Quaternion.FromToRotation(Vector2.up, -distance.normal);
    }
    private void Update()
    {
        if (grounded)
        {
            velocity.y = 0;

            if (Input.GetButtonDown("Jump"))
            {
                velocity.y = Mathf.Sqrt(2 * jumpHeight * Mathf.Abs(Physics2D.gravity.y));
            }
        }

        velocity.y += Physics2D.gravity.y * Time.deltaTime;

        float moveInput = Input.GetAxisRaw("Horizontal");

        if (moveInput != 0)
        {
            velocity.x = Mathf.MoveTowards(velocity.x, speed * moveInput, walkAcceleration * Time.deltaTime);
        }
        else
        {
            velocity.x = Mathf.MoveTowards(velocity.x, 0, groundDeacceleration * Time.deltaTime);
        }

        transform.Translate(velocity * Time.deltaTime);

        Collider2D[] hits = Physics2D.OverlapBoxAll(transform.position, boxCollider.size, 0);

        if (transform.position.y < -6)
        {
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        }

        grounded = false;
        foreach (Collider2D hit in hits)
        {
            if (hit == boxCollider)
            {
                continue;
            }

            ColliderDistance2D colliderDistance = hit.Distance(boxCollider);

            if (colliderDistance.isOverlapped)
            {
                transform.Translate(colliderDistance.pointA - colliderDistance.pointB);
                if (Vector2.Angle(colliderDistance.normal, Vector2.up) < 90 && velocity.y < 0)
                {
                    grounded = true;
                }
            }
        }
    }
Example #29
0
    void Update()
    {
        if (grounded)
        {
            velocity.y = 0;

            if (Input.GetButtonDown("Jump"))
            {
                velocity.y = Mathf.Sqrt(2 * jumpHeight * Mathf.Abs(Physics2D.gravity.y));
            }
        }

        velocity.y += Physics2D.gravity.y * Time.deltaTime;

        float move = Input.GetAxis("Horizontal");

        acceleration = grounded ? walkAcceleration : airAcceleration;
        deceleration = grounded ? groundDeceleration : 0;

        if (move != 0)
        {
            velocity.x = Mathf.MoveTowards(velocity.x, move * speed, acceleration * Time.deltaTime);
        }
        else
        {
            velocity.x = Mathf.MoveTowards(velocity.x, 0, deceleration * Time.deltaTime);
        }

        transform.Translate(velocity * Time.deltaTime);

        Collider2D[] hits = Physics2D.OverlapBoxAll(transform.position, boxCollider.size, 0);

        grounded = false;

        foreach (var hit in hits)
        {
            if (hit == boxCollider)
            {
                continue;
            }

            ColliderDistance2D colliderDistance = hit.Distance(boxCollider);

            if (colliderDistance.isOverlapped)
            {
                transform.Translate(colliderDistance.pointA - colliderDistance.pointB);
            }

            if (Vector2.Angle(colliderDistance.normal, Vector2.up) < 90 && velocity.y < 0)
            {
                grounded = true;
            }
        }
    }
Example #30
0
    // Update is called once per frame
    void Update()
    {
        float acceleration = grounded ? walkAcceleration : airAcceleration;
        float deceleration = grounded ? groundDeceleration : 0;

        moveInput = Input.GetAxisRaw("Horizontal");

        if (moveInput != 0)
        {
            velocity.x = Mathf.MoveTowards(velocity.x, speed * moveInput, acceleration * Time.deltaTime);
        }
        else
        {
            velocity.x = Mathf.MoveTowards(velocity.x, 0, deceleration * Time.deltaTime);
        }


        transform.Translate(velocity * Time.deltaTime);

        velocity.y += Physics2D.gravity.y * Time.deltaTime;

        colliderHits = Physics2D.OverlapBoxAll(transform.position, boxCollider.size, 0);



        grounded = false;
        foreach (Collider2D hit in colliderHits)
        {
            if (hit == boxCollider)
            {
                continue;
            }
            ColliderDistance2D colliderDistance = hit.Distance(boxCollider);
            if (colliderDistance.isOverlapped)
            {
                transform.Translate(colliderDistance.pointA - colliderDistance.pointB);
                if (Vector2.Angle(colliderDistance.normal, Vector2.up) < 90 && velocity.y < 0)
                {
                    grounded = true;
                }
            }
        }

        if (grounded)
        {
            velocity.y = 0;

            if (Input.GetKey(KeyCode.Space))
            {
                velocity.y = Mathf.Sqrt(2 * jumpHeight * Mathf.Abs(Physics2D.gravity.y));
            }
        }
    }