コード例 #1
0
    private void LookAhead()
    {
        isGroundAhead = Physics2D.Linecast(transform.position, LookAheadPoint.position, CollisionLayer);

        Debug.DrawLine(transform.position, LookAheadPoint.position, Color.green);
    }
コード例 #2
0
    // Update is called once per frame
    void Update()
    {
        // jump
        bool jump = Input.GetButtonDown(jumpInput);

        if (jump)
        {
            Vector2 groundPos = (Vector2)(transform.position - groundVector);
            // Use Linecast to see if there is ground under the player
            if (Physics2D.Linecast(transform.position, groundPos, 1 << LayerMask.NameToLayer(groundLayer)))
            {
                rigidbody2D.AddForce(new Vector2(0, jumpForce));
            }
        }

        // horizontal move
        float x;

        if (softenInput)
        {
            x = Input.GetAxis(horizontalInput);
        }
        else
        {
            x = stTools.GetAxisNorm(horizontalInput);
        }
        if (x > 0 && Physics2D.Linecast(transform.position, transform.position - rightVector,
                                        1 << LayerMask.NameToLayer(groundLayer)))
        {
            x = 0;
            print("!");
        }
        if (x < 0 && Physics2D.Linecast(transform.position, transform.position + rightVector,
                                        1 << LayerMask.NameToLayer(groundLayer)))
        {
            x = 0;
            print("!2");
        }
        Vector2 v = new Vector2(x * speed, rigidbody2D.velocity.y);

        rigidbody2D.velocity        = v;
        rigidbody2D.angularVelocity = 0;

        //facing
        if (v.x < 0)
        {
            if (facingRight)
            {
                facingRight = false;
                Vector3 s = gameObject.transform.localScale;
                s.x *= -1;
                transform.localScale = s;
            }
        }
        else if (v.x > 0)
        {
            if (!facingRight)
            {
                facingRight = true;
                Vector3 s = gameObject.transform.localScale;
                s.x *= -1;
                transform.localScale = s;
            }
        }
    }
    private void Raycast(PointerEventData eventData, List <RaycastResult> resultAppendList, Ray ray, bool checkForBlocking)
    {
        //This function is closely based on
        //void GraphicRaycaster.Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList)
        //WriteToLog("Got to start of raycast, canvas=" + canvas);

        if (canvas == null)
        {
            return;
        }
        float hitDistance = float.MaxValue;

        //WriteToLog("checkForBlocking=" + checkForBlocking + "blockingObjects=" + blockingObjects);

        if (checkForBlocking && blockingObjects != BlockingObjects.None)
        {
            float dist = eventCamera.farClipPlane;

            if (blockingObjects == BlockingObjects.ThreeD || blockingObjects == BlockingObjects.All)
            {
                var hits = Physics.RaycastAll(ray, dist, m_BlockingMask);

                if (hits.Length > 0 && hits[0].distance < hitDistance)
                {
                    hitDistance = hits[0].distance;
                }
            }

            if (blockingObjects == BlockingObjects.TwoD || blockingObjects == BlockingObjects.All)
            {
                var hits = Physics2D.GetRayIntersectionAll(ray, dist, m_BlockingMask);

                if (hits.Length > 0 && hits[0].fraction * dist < hitDistance)
                {
                    hitDistance = hits[0].fraction * dist;
                }
            }
        }

        m_RaycastResults.Clear();

        GraphicRaycast(canvas, ray, m_RaycastResults);
        //WriteToLog("canvas=" + canvas+ " m_RaycastResults.Count="+m_RaycastResults.Count);
        for (var index = 0; index < m_RaycastResults.Count; index++)
        {
            var  go            = m_RaycastResults[index].graphic.gameObject;
            bool appendGraphic = true;

            if (ignoreReversedGraphics)
            {
                // If we have a camera compare the direction against the cameras forward.
                var cameraFoward = ray.direction;
                var dir          = go.transform.rotation * Vector3.forward;
                appendGraphic = Vector3.Dot(cameraFoward, dir) > 0;
            }

            // Ignore points behind us (can happen with a canvas pointer)
            if (eventCamera.transform.InverseTransformPoint(m_RaycastResults[index].worldPos).z <= 0)
            {
                appendGraphic = false;
            }

            if (appendGraphic)
            {
                float distance = Vector3.Distance(ray.origin, m_RaycastResults[index].worldPos);

                if (distance >= hitDistance)
                {
                    continue;
                }

                var castResult = new RaycastResult
                {
                    gameObject = go,
                    module     = this,
                    distance   = distance,
                    index      = resultAppendList.Count,
                    depth      = m_RaycastResults[index].graphic.depth,

                    worldPosition = m_RaycastResults[index].worldPos
                };
                resultAppendList.Add(castResult);
            }
        }
    }
コード例 #4
0
    public void CollisionMove()
    {
        float deltaX = currentSpeed.x;
        float deltaY = currentSpeed.y;

        Vector2 p = transform.position;

        // Check y directions
        int yDir = (int)Mathf.Sign(deltaY);

        for (int i = 0; i < divisionsX; i++)
        {
            float x = (p.x + center.x - size.x / 2) + i * size.x / (divisionsX - 1);
            float y = p.y + center.y + yDir * size.y / 2;

            Ray2D ray = new Ray2D(new Vector2(x, y), new Vector2(0, yDir));
            Debug.DrawRay(ray.origin, ray.direction);
            RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Abs(deltaY) + skin, collisionMask);
            if (hit.collider)
            {
                float d = Vector2.Distance(ray.origin, hit.point);

                if (yDir < 0)
                {
                    grounded       = true;
                    currentSpeed.y = 0;
                }

                if (d > skin)
                {
                    deltaY = yDir * (d - skin);
                }
                else
                {
                    deltaY = 0;
                }
                break;
            }
        }

        // Check x directions
        int xDir = (int)Mathf.Sign(deltaX);

        for (int i = 0; i < divisionsY; i++)
        {
            float x = p.x + center.x + xDir * size.x / 2;
            float y = (p.y + center.y - size.y / 2) + i * size.y / (divisionsY - 1);

            Ray2D ray = new Ray2D(new Vector2(x, y), new Vector2(xDir, 0));
            Debug.DrawRay(ray.origin, ray.direction);
            RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Abs(deltaX) + skin, collisionMask);
            if (hit.collider)
            {
                float d = Vector2.Distance(ray.origin, hit.point);
                wallCollision  = true;
                currentSpeed.x = 0;
                if (d > skin)
                {
                    deltaX = xDir * (d - skin);
                }
                else
                {
                    deltaX = 0;
                }
                break;
            }
        }

        // Check player velocity angle
        if (!grounded && !wallCollision)
        {
            Vector2 playerDir = new Vector2(deltaX, deltaY).normalized;
            Vector2 o         = new Vector2(p.x + center.x + Mathf.Sign(deltaX) * size.x / 2, p.y + center.y + Mathf.Sign(deltaY) * size.y / 2);
            Ray2D   ray       = new Ray2D(o, playerDir);
            Debug.DrawRay(ray.origin, ray.direction);
            RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Sqrt(deltaX * deltaX + deltaY * deltaY), collisionMask);
            if (hit.collider)
            {
                grounded = true;
                deltaY   = 0;
            }
        }

        transform.Translate(new Vector2(deltaX, deltaY));
    }
コード例 #5
0
ファイル: Controller2D.cs プロジェクト: Cbunz/ShieldWield_1.0
    private void VerticalCollisions(ref Vector2 moveAmount)
    {
        float directionY = Mathf.Sign(moveAmount.y);
        float rayLength  = Mathf.Abs(moveAmount.y) + skinWidth;

        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, collisionMask);

            Debug.DrawRay(rayOrigin, Vector2.up * directionY, Color.red);

            if (hit)
            {
                if (hit.collider.tag == "Through")
                {
                    if (directionY == 1 || hit.distance == 0)
                    {
                        continue;
                    }
                    if (collisions.fallingThroughPlatform)
                    {
                        continue;
                    }
                    if (playerInput.y == -1)
                    {
                        collisions.fallingThroughPlatform = true;
                        Invoke("ResetFallingThroughPlatform", fallingThroughPlatformResetTimer);
                        continue;
                    }
                }
                moveAmount.y = (hit.distance - skinWidth) * directionY;
                rayLength    = hit.distance;

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

                collisions.below = directionY == -1;
                collisions.above = directionY == 1;
            }
        }

        if (collisions.climbingSlope)
        {
            float directionX = Mathf.Sign(moveAmount.x);
            rayLength = Mathf.Abs(moveAmount.x) + skinWidth;
            Vector2      rayOrigin = ((directionX == -1) ? raycastOrigins.bottomLeft : raycastOrigins.bottomRight) + Vector2.up * moveAmount.y;
            RaycastHit2D hit       = Physics2D.Raycast(rayOrigin, Vector2.right * directionX, rayLength, collisionMask);

            if (hit)
            {
                float slopeAngle = Vector2.Angle(hit.normal, Vector2.up);
                if (slopeAngle != collisions.slopeAngle)
                {
                    moveAmount.x          = (hit.distance * skinWidth) * directionX;
                    collisions.slopeAngle = slopeAngle;
                }
            }
        }
    }
コード例 #6
0
    void OnCollisionEnter2D(Collision2D collision)
    {
        int damagePlayer = 0;

        // Ignore collision when player is invincible
        Physics2D.IgnoreCollision(collision.gameObject.GetComponent <Collider2D>(), GetComponent <Collider2D>(), isInvincible);
        if (!isInvincible)
        {
            // Collision with enemy
            EnemyScript enemy = collision.gameObject.GetComponent <EnemyScript>();
            if (enemy != null && collision.gameObject.GetComponent <BossScript>() == null)
            {
                // Kill the enemy
                HealthScript enemyHealth = enemy.GetComponent <HealthScript>();
                if (enemyHealth != null)
                {
                    damagePlayer = enemyHealth.hp / 3;
                    if (shieldLevel + 1 >= damagePlayer)
                    {
                        enemyHealth.Damage(enemyHealth.hp); // kill enemy
                    }
                }
                if (damagePlayer < 1)
                {
                    damagePlayer = 1;
                }
            }
        }

        // Is this a bonus?
        CollectableScript collectable = collision.gameObject.GetComponentInChildren <CollectableScript>();

        if (collectable != null)
        {
            // Is this a shield bonus?
            ShieldScript shield = collision.gameObject.GetComponent <ShieldScript>();
            if (shield != null)
            {
                shieldLevel     = shield.shieldLevel;
                lastShieldLevel = shieldLevel;
                updateShieldUi();
                updateLifeUi(false);
                SoundEffectsHelper.Instance.MakeShieldSound(true);
                Destroy(shield.gameObject); // Remember to always target the game object, otherwise you will just remove the script
            }
            else
            {
                SoundEffectsHelper.Instance.MakePickupSound();
            }
            // Is this a weapon bonus?
            changeWeapon(collision.gameObject);
            // Is this a bomb bonus?
            BombScript bomb = collision.gameObject.GetComponent <BombScript>();
            if (bomb != null)
            {
                if (nbBombs < MAX_BOMB)
                {
                    nbBombs++;
                    GameHelper.Instance.pickupBomb();
                }
                SoundEffectsHelper.Instance.MakePickupSound();
            }

            GameHelper.Instance.collectBonus(collectable.getId());
            Destroy(collision.gameObject); // Remember to always target the game object, otherwise you will just remove the script
        }

        // Damage the player if necessery
        if (this.takeDamage(damagePlayer))
        {
            GetComponent <HealthScript>().Damage(1);
        }
    }
コード例 #7
0
    // Update is called once per frame
    void Update()
    {
        // Inisiasi status pantulan lintasan, yang hanya akan ditampilkan jika lintasan bertumbukan dengan objek tertentu.
        bool drawBallAtCollision = false;

        // Titik tumbukan yang digeser, untuk menggambar ballAtCollision
        Vector2 offsetHitPoint = new Vector2();

        // Tentukan titik tumbukan dengan deteksi pergerakan lingkaran
        RaycastHit2D[] circleCastHit2DArray = Physics2D.CircleCastAll(ballRigidbody.position, ballCollider.radius,
                                                                      ballRigidbody.velocity.normalized);
        // Untuk setiap titik tumbukan, ...
        foreach (RaycastHit2D circleCastHit2D in circleCastHit2DArray)
        {
            // Jika terjadi tumbukan, dan tumbukan tersebut tidak dengan bola
            // (karena garis lintasan digambar dari titik tengah bola)...
            if (circleCastHit2D.collider != null &&
                circleCastHit2D.collider.GetComponent <BallControl>() == null)
            {
                // Garis lintasan akan digambar dari titik tengah bola saat ini ke titik tengah bola pada saat tumbukan,
                // yaitu sebuah titik yang di-offset dari titik tumbukan berdasar vektor normal titik
                // tersebut sebesar
                // jari-jari bola.

                // Tentukan titik tumbukan
                Vector2 hitPoint = circleCastHit2D.point;

                // Tentukan normal di titik tumbukan
                Vector2 hitNormal = circleCastHit2D.normal;

                // Tentukan offsetHitPoint, yaitu titik tengah bola pada saat bertumbukan
                offsetHitPoint = hitPoint + hitNormal * ballCollider.radius;

                // Gambar garis lintasan dari titik tengah bola saat ini ke titik tengah bola pada saat bertumbukan
                DottedLine.DottedLine.Instance.DrawDottedLine(ball.transform.position, offsetHitPoint);

                // Kalau bukan sidewall, gambar pantulannya
                if (circleCastHit2D.collider.GetComponent <SideWall>() == null)
                {
                    // Hitung vektor datang
                    Vector2 inVector = (offsetHitPoint - ball.TrajectoryOrigin).normalized;

                    // Hitung vektor keluar
                    Vector2 outVector = Vector2.Reflect(inVector, hitNormal);

                    // Hitung dot product dari outVector dan hitNormal. Digunakan supaya garis lintasan ketika
                    // terjadi tumbukan tidak digambar.
                    float outDot = Vector2.Dot(outVector, hitNormal);
                    if (outDot > -1.0f && outDot < 1.0)
                    {
                        // Gambar lintasan pantulannya
                        DottedLine.DottedLine.Instance.DrawDottedLine(
                            offsetHitPoint,
                            offsetHitPoint + outVector * 10.0f);

                        // Untuk menggambar bola "bayangan" di prediksi titik tumbukan
                        drawBallAtCollision = true;
                    }
                }

                // Hanya gambar lintasan untuk satu titik tumbukan, jadi keluar dari loop
                break;
            }
        }
        // Jika true, ...
        if (drawBallAtCollision)
        {
            // Gambar bola "bayangan" di prediksi titik tumbukan
            ballAtCollision.transform.position = offsetHitPoint;
            ballAtCollision.SetActive(true);
        }
        else
        {
            // Sembunyikan bola "bayangan"
            ballAtCollision.SetActive(false);
        }
    }
コード例 #8
0
ファイル: PlayerController.cs プロジェクト: oushiff/Overnight
	void FixedUpdate()
	{
		bool isSnowClick = heroTransform.isSnowTransform;

		if (isSnow)
			lastPosition = transform.position;
		
		if (isSnowClick && GameManager.Instance.isCameraFix) {
			heroTransform.isSnowTransform = false;
			isSnowClick = false;
			isSnow = !isSnow;
			if (!isSnow) {
				Debug.Log ("Snow Disappear!!!!");
				//cloudObject.SetActive (false);
				//Destroy(cloudObject);
				GameManager.Instance.Status = "PlayerCloud";
				transform.position = new Vector3(cloudController.lastPosition.x, outOfScreenY, 0);
			} else {
				Debug.Log ("Snow re-appear!!!!");
				//GameObject cloudObject = GameObject.Find ("CloudBall");
				//cloudObject.SetActive (true);
				transform.position = cloudController.lastPosition;
				GameManager.Instance.Status = "PlayerSnow";
				//GameObject.Instantiate(cloudObject,transform.position/* new Vector3(5.6f,12.5f,0f)*/,Quaternion.identity);
			}
			GameManager.Instance.isCameraFix = false;
			GameManager.Instance.isCameraReturn = true;
		}

		if (!isSnow) {
			transform.position = new Vector3(cloudController.lastPosition.x, outOfScreenY, 0);
			return;
		}

		//Store the current horizontal input in the float moveHorizontal.
		float moveHorizontal = Input.GetAxis ("Horizontal") * speedFactor;

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

		movement = new Vector2 (moveHorizontal, 0); 

		movement.x = joystick.Horizontal() * speedFactor;

		if (movement.x > MaxSpeed)
			movement.x = MaxSpeed;
		else if (movement.x < -MaxSpeed)
			movement.x = -MaxSpeed;

		movement.y = 0;//joystick.Vertical();
		//Debug.Log (" spped " + movement.y);


        if (Input.GetKeyDown(KeyCode.Space))
            tryJump();


		bool isJumpClick = heroJump.isClickBool;

		if (isJumpClick) {
			heroJump.isClickBool = false;
			isJumpClick = false;
			isJump = !isJump;
			tryJump ();
		}

		// run
		//rb2d.AddForce (new Vector2(movement.x, 0) * speed);
		rb2d.velocity = new Vector2 (movement.x , rb2d.velocity.y);

		//jump
		Collider2D[] colliders = Physics2D.OverlapCircleAll(rb2d.position, ballRadius,LayerMask.GetMask("surface"));
		//Call the AddForce function of our Rigidbody2D rb2d supplying movement multiplied by speed to move our player.

//		for (int i = 0; i < colliders.Length; i++)
//		{
//			if (colliders [i].gameObject != gameObject) {
//				m_Grounded = true;
//				break;
//			}
//		}
		
		
		if (colliders.Length >= 1) {
			m_Grounded = true;
			//Debug.Log("colliders.Length = " + colliders.Length);
		} else {
			//Debug.Log("colliders.Length = " + colliders.Length);
			m_Grounded = false;
		}




		//transform.Rotate (new Vector3 (0, 0, -45) * Time.deltaTime);


	}
コード例 #9
0
    // Update is called once per frame
    void Update()
    {
        if (startbossfight)
        {
            startpoint = transform.position;
            isGrounded = Physics2D.OverlapCircle(feetpos.position, checkRadius, whatIsGround);
            bossanim.SetBool("isGrounded", isGrounded);
            if (isGrounded && !prevGrounded)
            {
                GameObject cam = GameObject.FindGameObjectWithTag("MainCamera");
                FindObjectOfType <SFX>().Play("boss_stomp");
                cam.GetComponent <Animator>().SetTrigger("shake");
            }
            prevGrounded = isGrounded;
            if (isGrounded && boss_state == 1)
            {
                rb.velocity = new Vector2(0 * speed, rb.velocity.y);
                if ((transform.position.x < player.position.x) && !facingright)
                {
                    flip();
                }
                if ((transform.position.x > player.position.x) && facingright)
                {
                    flip();
                }
            }
            else if (die)
            {
                rb.velocity = new Vector2(0 * speed, rb.velocity.y);
            }
            else
            {
                rb.velocity = new Vector2(movedir * speed, rb.velocity.y);
            }
            time_to_changestate -= Time.deltaTime;
            if (time_to_changestate <= 0 && (isGrounded == true || isFlying == true))
            {
                changestate();
                time_to_changestate = changetime;
            }
            switch (boss_state)
            {
            case 1:
                if (timebtwjump <= 0)
                {
                    jump();
                    timebtwjump = jumptime;
                }
                else
                {
                    timebtwjump -= Time.deltaTime;
                }
                break;

            case 2:
                if (!isFlying)
                {
                    isFlying = true;
                    bossanim.SetBool("fly", isFlying);
                    bossanim.SetTrigger("jump");
                    rb.velocity = Vector2.up * jumpforce;
                }
                flying();
                if (timebtwattack <= 0)
                {
                    rb.velocity = new Vector2(0 * speed, rb.velocity.y);
                    bossanim.SetTrigger("attack");
                    attack(numberofBullet);
                    timebtwattack = attacktime;
                }
                else
                {
                    timebtwattack -= Time.deltaTime;
                }
                break;

            case 3:
                speed = 0f;
                if (timebtwattack <= 0)
                {
                    bossanim.SetTrigger("attack");
                    spawnvirus();
                    timebtwattack = attacktime;
                }
                else
                {
                    timebtwattack -= Time.deltaTime;
                }
                break;

            case 4:
                speed = 0f;
                if (c_attacktimecounter <= 0)
                {
                    if (num > 5)
                    {
                        num = 0;
                    }
                    bossanim.SetTrigger("attack");
                    circularattack(c_numberofBullet[num]);
                    c_attacktimecounter = c_attacktime;
                    num++;
                }
                else
                {
                    c_attacktimecounter -= Time.deltaTime;
                }
                break;

            case 5:
                focusonboss();
                bossanim.SetTrigger("die");
                break;

            default: break;
            }
        }
    }
コード例 #10
0
ファイル: boyController.cs プロジェクト: WaitesC/CrunchTime
    private void Update()
    {
        // Use GetAxisRaw to ensure our input is either 0, 1 or -1.
        float moveInput = Input.GetAxisRaw("Horizontal");



        if (grounded)
        {
            velocity.y = 0;

            if (Input.GetButtonDown("Jump"))
            {
                // Calculate the velocity required to achieve the target jump height.
                velocity.y = Mathf.Sqrt(2 * jumpHeight * Mathf.Abs(Physics2D.gravity.y));
            }
        }

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

        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);
        }

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

        transform.Translate(velocity * Time.deltaTime);

        grounded = 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)
                {
                    grounded = true;
                }
            }
        }
    }
コード例 #11
0
ファイル: BasicEnemyAI.cs プロジェクト: chrsjwilliams/Prism
    /*--------------------------------------------------------------------------------------*/
    /*																						*/
    /*	FixedUpdate: Runs every fixed interval. Interval can be changed in Unity.			*/
    /*																						*/
    /*--------------------------------------------------------------------------------------*/
    void FixedUpdate()
    {
        if (!NextLevel.loadingLevel.isLoading)
        {
            if (target == null)
            {
                if (!_SerahcingForPlayer)
                {
                    _SerahcingForPlayer = true;
                    StartCoroutine(SearchForPlayer());
                }
                return;
            }

            if (path == null)
            {
                return;
            }

            if (_CurrentWayPoint >= path.vectorPath.Count)
            {
                if (pathIsEnded)
                {
                    return;
                }

                pathIsEnded = true;
                return;
            }

            pathIsEnded = false;

            //	Only move when active
            if (!isOff)
            {
                //	Movement when player is in sight or when not in the light
                if ((tag != "Enemy_BLCK" || !inLight) && followPlayer)
                {
                    //	Finds direction to next way point
                    Vector3 direction = (path.vectorPath [_CurrentWayPoint] - transform.position).normalized;
                    direction *= speed * Time.fixedDeltaTime;

                    //	Moves the AI

                    _Rigidbody2D.AddForce(direction, fMode);

                    float distance = Vector3.Distance(transform.position, path.vectorPath [_CurrentWayPoint]);

                    if (distance < nextWayPointDistance)
                    {
                        _CurrentWayPoint++;
                        return;
                    }
                }

                //	Movement for YELLOW enemies (left and right)
                if (!followPlayer && tag == "Enemy_YLLW")
                {
                    Vector2 lineCastPosition = transform.position.toVector2() - transform.right.toVector2() * _Width + Vector2.up * _Height;

                    bool isGrounded = Physics2D.Linecast(lineCastPosition, lineCastPosition + Vector2.down, enemyMask);
                    bool isBlocked  = Physics2D.Linecast(lineCastPosition, lineCastPosition - transform.right.toVector2() * 0.05f, enemyMask);

                    //	If not grounded or blocked then turn around
                    if (!isGrounded || isBlocked)
                    {
                        Vector3 currentRotation = transform.eulerAngles;
                        currentRotation.y    += 180;
                        transform.eulerAngles = currentRotation;
                    }

                    //	Always move "forward" when not following player
                    Vector2 newVelcotiy = _Rigidbody2D.velocity;
                    newVelcotiy.x = -transform.right.x * moveSpeed * Time.fixedDeltaTime;

                    _Rigidbody2D.velocity = newVelcotiy;
                }

                //	Movement for CYAN enemies (up and down)
                if (!followPlayer && tag == "Enemy_CYAN")
                {
                    Vector2 lineCastPosition = transform.position.toVector2() - transform.right.toVector2() * 0.0f * _Width + Vector2.up * _Height;

                    bool isBlockedBottom = Physics2D.Linecast(lineCastPosition, lineCastPosition + Vector2.down * 0.9f, enemyMask);
                    bool isBlockedTop    = Physics2D.Linecast(lineCastPosition, lineCastPosition + Vector2.up * 0.05f, enemyMask);

                    //	If not grounded or bloacked then turn around
                    if (isBlockedBottom || isBlockedTop)
                    {
                        moveSpeed *= -1;
                    }

                    //	Always move forward when not following player
                    Vector2 newVelcotiy = _Rigidbody2D.velocity;
                    newVelcotiy.y = -transform.up.y * moveSpeed * Time.fixedDeltaTime;

                    _Rigidbody2D.velocity = newVelcotiy;
                }
            }
        }
    }
コード例 #12
0
    // Update is called once per frame
    void Update()
    {
        Vector3 vec = Vector3.right * transform.localScale.x;

        //int offset = 0;


        for (int i = 0; i < m_shootingSide.Length; i++)
        {
            for (int j = 0; j < m_halfSideBulletNumber; j++)
            {
                Vector3 angle = Quaternion.AngleAxis(m_shootingSide [i] * (j + 1) * m_angleInterval, Vector3.forward) * vec;
                Vector3 end   = transform.position + angle * m_rayLength;
                Debug.DrawLine(transform.position, end, Color.red);

                hit = Physics2D.Raycast(transform.position, angle, m_rayLength, m_layer);
                if (hit.collider != null)
                {
                    //m_vertices [i * m_halfSideBulletNumber + j + offset] = new Vector2 (hit.point.x - transform.position.x, hit.point.y - transform.position.y);
                    if (hit.collider.name == "Hero")
                    {
                        LoadController load = GameObject.Find("SavaPoint").GetComponent <LoadController> ();
                        load.Reload(hit.collider.gameObject);
                    }
                }
                else
                {
                    //m_vertices [i * m_halfSideBulletNumber + j + offset] = angle * m_rayLength;
                }
                //input
                //求法线向量与物体上方向向量点乘,结果为1或-1,修正旋转方向
                //float aAngle = Vector3.Angle (Vector3.right, angle) * Mathf.Sign (Vector3.Dot (angle, Vector3.up));
                //aSimpleBullet.transform.Rotate (Vector3.forward, aAngle);
                //aSimpleBullet.m_isPlayerFire = m_isPlayerFire;
                //aSimpleBullet.InitBullet (angle, m_bulletSpeed, m_bulletAttack, m_bulletDuration, m_bulletRepelDistance);
            }
            //offset += 1;
        }

        Debug.DrawLine(transform.position, (transform.position + vec * m_rayLength), Color.red);
        hit = Physics2D.Raycast(transform.position, vec * m_rayLength, m_rayLength, m_layer);
        if (hit.collider != null)
        {
            //m_vertices [m_halfSideBulletNumber -2] = new Vector2 (hit.point.x - transform.position.x, hit.point.y - transform.position.y);

            if (hit.collider.name == "Hero")
            {
                LoadController load = GameObject.Find("SavaPoint").GetComponent <LoadController> ();
                load.Reload(hit.collider.gameObject);
            }
        }
        else
        {
            //m_vertices [(i + 1) * m_halfSideBulletNumber] = vec * m_rayLength;
        }
        //m_vertices [m_vertices.Length - 1] = Vector3.zero;

        //Vector2 temp = m_vertices [1];
        //m_vertices [1] = m_vertices [0];
        //m_vertices [0] = temp;

        //Vector3 [] vertices3D = System.Array.ConvertAll<Vector2, Vector3> (m_vertices, v => v);

        //// Use the triangulator to get indices for creating triangles
        //Triangulator triangulator = new Triangulator (m_vertices);
        //int [] indices = triangulator.Triangulate ();


        //Color [] colors = new Color [vertices3D.Length];
        //for (int i = 0; i < colors.Length; i++) {
        //	colors [i] = Color.red;
        //	colors [i].a = 0.5f;
        //}

        //// Create the mesh
        //var mesh = new Mesh {
        //	vertices = vertices3D,
        //	triangles = indices,
        //	colors = colors
        //};


        //mesh.RecalculateNormals ();
        //mesh.RecalculateBounds ();



        //filter.mesh = mesh;
    }
コード例 #13
0
ファイル: Player.cs プロジェクト: MonsiDev/myplat
 void FixedUpdate()
 {
     isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
 }
コード例 #14
0
 void FixedUpdate()
 {
     Grounded = Physics2D.OverlapCircle(GroundCheck.position, GroundCheckRadius, WhatIsGround);
 }
コード例 #15
0
 private bool Cast(Collider2D col)
 {
     return(!Physics2D.Raycast(Origin.position, col.transform.position - Origin.position, Vector2.Distance(col.transform.position, Origin.position), LayerMask).collider);
 }
コード例 #16
0
 void FixedUpdate()
 {
     Walled  = Physics2D.OverlapCircle(wallCheck.position, WallRadius, WhatIsWall);
     notAtEg = Physics2D.OverlapCircle(egCheck.position, WallRadius, WhatIsWall);
 }
コード例 #17
0
    protected override IEnumerator abilityActionSequence()
    {
        caster.rb2D.AddForce(direction * abilityVelocity / Time.timeScale);

        while (!caster.getAttackTrigger().hasAttackTriggered())
            yield return null;

        caster.getAttackTrigger().resetTrigger();

        //Check if attack can go through
        if (!caster.isDead())
        {

            Vector2 newPos = new Vector2(caster.transform.position.x, caster.transform.position.y + caster.objectHeight / 2);

            RaycastHit2D[] hitObject = Physics2D.RaycastAll(newPos, direction, abilityRange, CMoveCombatable.attackMask, -10, 10);
            Debug.DrawRay(newPos, direction * abilityRange, Color.red, 3f);

            bool hitTarget = false;

            //If the Raycast hits an object on the layer Enemy
            foreach (RaycastHit2D r in hitObject)
            {

                if (r && r.transform.gameObject != caster.gameObject)
                {
                    //If an object has been hit first
                    if (r.transform.gameObject.tag == "Object")
                    {
                        if (r.collider.isTrigger)
                            continue;
                        else
                            break;
                    }

                    //Hit attack
                    CHitable objectHit = r.transform.gameObject.GetComponentInParent<CHitable>();

                    if (objectHit.tag == caster.tag)
                        continue;

                    //Apply damage and knockback
                    objectHit.setAttacker(caster);
                    objectHit.knockback(pos, abilityKnockback, objectHit.objectHeight); //Need to use original pos for knockback so the position of where you attacked from is the knockback
                    objectHit.knockUp(pos, abilityKnockback, abilityKnockUp, objectHit.objectHeight);
                    objectHit.loseHealth(abilityDamage);

                    CMoveCombatable targetHit = r.transform.gameObject.GetComponentInParent<CMoveCombatable>();

                    if (targetHit != null)
                    {
                        targetHit.causeOfDeath = causeOfDeath;
                    }

                    caster.audioSource.clip = caster.attackSound;
                    caster.audioSource.Play();
                    caster.attackHit();

                    hitTarget = true;
                    break;
                }
            }

            if (!hitTarget)
            {
                caster.audioSource.clip = caster.missSound;
                caster.audioSource.Play();
            }

            if (caster.pauseAfterAttack < 0.5f)
                yield return new WaitForSeconds(0.5f);
            else
                yield return new WaitForSeconds(caster.pauseAfterAttack);
        }
        caster.canMove = true;
        caster.attacking = false;
        caster.canCombo = false;
    }
コード例 #18
0
ファイル: MovimentAndroid.cs プロジェクト: Trope100/TFG
    // FixUpdate is called once 0.02 seconds each frame (This can be modified in edit > Project Settings > Time > Fixed Timestep)
    void FixedUpdate()
    {
        //MOVIMIENT HORIZONTAL
        inputX = Input.GetAxis("Horizontal");


        if (!agachado && !mirarArriba)
        {
            transform.position += new Vector3(inputX * velX * Time.deltaTime, 0, 0);


            posIniIFin         = Mathf.Clamp(transform.position.x, -14.32f, 205f);
            transform.position = new Vector3(posIniIFin, transform.position.y, 0);

            if (inputX > 0)
            {
                transform.localScale = new Vector3(1, 1, 1);
            }

            if (inputX < 0)
            {
                transform.localScale = new Vector3(-1, 1, 1);
            }
        }

        if (inputX != 0)
        {
            animator.SetFloat("velX", 1);
        }
        else
        {
            animator.SetFloat("velX", 0);
        }

        //SALT

        enSuelo = Physics2D.OverlapCircle(pie.position, radioPie, suelo);


        //AJUPITSE

        if (enSuelo && (Input.GetKey(KeyCode.DownArrow) || Input.GetButton("Vertical")))
        {
            agachado = true;
            animator.SetBool("agachado", true);


            gameObject.GetComponent <CircleCollider2D>().offset = new Vector2(0f, 0.16f);
            gameObject.GetComponent <CircleCollider2D>().radius = 0.15f;
        }
        else
        {
            gameObject.GetComponent <CircleCollider2D>().offset = new Vector2(0.03853655f, 0.2803588f);
            gameObject.GetComponent <CircleCollider2D>().radius = 0.2048309f;
            if (Input.GetKeyUp(KeyCode.DownArrow))
            {
                gameObject.GetComponent <CircleCollider2D>().offset = new Vector2(0.03853655f, 0.2803588f);
                gameObject.GetComponent <CircleCollider2D>().radius = 0.2048309f;
            }

            agachado = false;
            animator.SetBool("agachado", false);
        }



        //MIRAR AMUNT
        if (inputX == 0)  //Si no me muevo
        {
            if (enSuelo && (Input.GetKey(KeyCode.UpArrow) || Input.GetButton("Fire3")))
            {
                mirarArriba = true;
                animator.SetBool("mirarArriba", true);
            }
            else
            {
                mirarArriba = false;
                animator.SetBool("mirarArriba", false);
            }
        }

        //CAIGUDA
        caida = rb.velocity.y;

        if (caida != 0 || caida == 0)
        {
            animator.SetFloat("velY", caida);
        }



        //CORRER

        if (inputX != 0)
        {
            if (Input.GetKey(KeyCode.X) || Input.GetButton("Fire2"))
            {
                run  = true;
                velX = 0f;
                animator.SetBool("run", true);
            }


            if (!Input.GetKey(KeyCode.X) || !Input.GetButton("Fire2"))
            {
                velX = 4f;
                run  = false;
                animator.SetBool("run", false);
            }
        }
        else
        {
            run = false;
            animator.SetBool("run", false);
        }
    }
コード例 #19
0
    /* Creates grid map based on the start and end position of the grid */
    private void CreateMap()
    {
        //Find positions for start and end of map
        float startX = MapStartPosition.x;
        float startY = MapStartPosition.y;
        float endX   = MapEndPosition.x;
        float endY   = MapEndPosition.y;

        //Find tile width and height
        width  = (int)Mathf.Floor((endX - startX) / Tilesize);
        height = (int)Mathf.Floor((endY - startY) / Tilesize);

        //Create double array representing the nodes in the grid
        Map = new AStarNode[width, height];

        Vector2 nodePosition = new Vector2();
        Vector2 boxCastSize  = new Vector2(Tilesize / 2, Tilesize / 2);

        //Create nodes in the map
        for (int i = 0; i < width; i++)
        {
            for (int j = 0; j < height; j++)
            {
                //Compute nodes position
                nodePosition.x = startX + (i * Tilesize);
                nodePosition.y = startY + (j * Tilesize);

                //Create a node at that position
                Map[i, j] = new AStarNode(nodePosition, true);

                //Ray cast to see if there is a 2D collider at that position
                RaycastHit2D[] hit2D = Physics2D.BoxCastAll(nodePosition, boxCastSize, 0f, Vector2.left, 0f);

                //For any 2D collider found at the position, check if the associated game object
                //is tagged with one of the disallowed tags
                foreach (RaycastHit2D h in hit2D)
                {
                    //If tagged with a tag on the disallowed tags list, make the node
                    //non-walkable
                    if (CheckForDisallowedTag(h.transform))
                    {
                        Map[i, j].walkable = false;
                        break;
                    }
                }
            }
        }

        //Given the 2D array of nodes, connect the neighbouring tiles.  There can be a maximum of
        //eight connections from a given node: up and down, left and right,  left-down, left-up, right-down and right-up
        for (int i = 0; i < width; i++)
        {
            for (int j = 0; j < height; j++)
            {
                //Get the node from the map
                AStarNode nodeLeft = Map[i, j];

                //Check if the node is walkable
                if (!nodeLeft.walkable)
                {
                    continue;
                }

                //Cycle through all the neighbours of the node (based on 2D arrangement)
                for (int ni = i - 1; ni <= i + 1; ni++)
                {
                    if (ni < 0 || ni >= width)
                    {
                        continue;
                    }
                    for (int nj = j - 1; nj <= j + 1; nj++)
                    {
                        if (nj < 0 || nj >= height)
                        {
                            continue;
                        }

                        AStarNode nodeRight = Map[ni, nj];

                        //Do not connect to self
                        if (nodeRight == nodeLeft)
                        {
                            continue;
                        }

                        //If the neighbour is not walkable, do not connect
                        if (!nodeRight.walkable)
                        {
                            continue;
                        }

                        //Do not connect the same node twice
                        if (nodeLeft.isConnected(nodeRight))
                        {
                            continue;
                        }
                        //The weight of the connection is the Eucledean distance between
                        //the nodes
                        float cost = Vector2.Distance(nodeLeft.position, nodeRight.position);

                        //Connect the nodes
                        nodeLeft.connect(nodeRight, cost);
                    }
                }
                //Sort the game nodes by cost - this will speed up pathfinding later on
                nodeLeft.neighbours = nodeLeft.neighbours.OrderBy(x => x.cost).ToList();
            }
        }
    }
コード例 #20
0
 private bool CanGetUp()
 {
     return(Physics2D.OverlapBox(transform.position + attributes.colliderBounds.center, attributes.colliderBounds.extents - (Vector3.one * .001f), 0, contactFilter, overlapBuffer) == 0);
 }
コード例 #21
0
    public void SideCheck()
    {
        int rays = 4;

        //bool firstLeft = false;
        //bool lastLeft = false;
        //bool firstRight = false;
        //bool lastRight = false;

        for (int i = 0; i < rays; i++)
        {
            //left

            Vector2 leftPos = new Vector2(_Collider.bounds.min.x, _Collider.bounds.min.y) + new Vector2(0, 1) * _Collider.bounds.size.y / (rays - 1) * i;
            Debug.DrawRay(leftPos, -transform.right * 0.2f, Color.red);
            RaycastHit2D leftHit = Physics2D.Raycast(leftPos, -transform.right, 0.2f, _StandableMasks);
            if (leftHit)
            {
                //if (i == 0)
                //{
                //    firstLeft = true;
                //}
                //if (i == rays -1)
                //{
                //    lastLeft = true;
                //}

                if (_Velocity.x < 0)
                {
                    _Velocity.x = 0;
                }
            }

            //right

            Vector2 rightPos = new Vector2(_Collider.bounds.max.x, _Collider.bounds.min.y) + new Vector2(0, 1) * _Collider.bounds.size.y / (rays - 1) * i;
            Debug.DrawRay(rightPos, transform.right * 0.2f, Color.red);
            RaycastHit2D rightHit = Physics2D.Raycast(rightPos, transform.right, 0.2f, _StandableMasks);
            if (rightHit)
            {
                //if (i == 0)
                //{
                //    firstRight = true;
                //}
                //if (i == rays -1)
                //{
                //    lastRight = true;
                //}

                if (_Velocity.x > 0)
                {
                    _Velocity.x = 0;
                }
            }
        }

        //if (firstLeft == true && lastLeft == false)
        //{
        //    if (InputManager.instance.HorizontalDirection() == -1)
        //    {
        //        _Velocity.y = 10;
        //    }
        //}
        //else
        //{

        //}

        //if (firstRight == true && lastRight == false)
        //{
        //    if (InputManager.instance.HorizontalDirection() == 1)
        //    {
        //        _Velocity.y = 10;
        //    }
        //}
        //else
        //{

        //}
    }
コード例 #22
0
    void VerticalCollisions(ref Vector2 moveAmount, bool jumpInputDown)       //similiar to horizontal but with a few differences, especially with through platforms. Also stores standing on top of if on one
    {
        float directionY = Mathf.Sign(moveAmount.y);
        float rayLength  = Mathf.Abs(moveAmount.y) + SKIN_WIDTH;

        if (Mathf.Abs(moveAmount.y) < SKIN_WIDTH)
        {
            rayLength = 2 * SKIN_WIDTH;
        }

        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, collisionMask);

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

            if (hit)
            {
                if (hit.collider.tag == "Through")
                {
                    if (directionY == 1 || hit.distance == 0)                       //if moving up, continue to next ray. (only collides of moving down)
                    {
                        continue;
                    }
                    if (collisions.fallingThrough == true && collisions.fallingThroughPlatform == hit.collider)                       //if the user if falling through the platform
                    {
                        continue;
                    }
                    if (directionalInput.y == -1)                       //enables the user to drop through the platform after they press down
                    {
                        collisions.readyToFallThrough = true;
                    }
                    if (directionalInput.y == -1 && jumpInputDown)                       //drops through the platform
                    {
                        if (hit.collider == collisions.fallingThroughPlatform)
                        {
                            collisions.fallingThrough = true;
                            continue;
                        }
                    }
                }

                collisions.fallingThrough         = false;         //if made it through the last if statement, the user isn't falling through the platform
                collisions.fallingThroughPlatform = hit.collider;  //sets the platform the user is standing on top of, important for if the user does fall through it, it stores it and resets it when landing on another platform
                moveAmount.y = (hit.distance - SKIN_WIDTH) * directionY;
                rayLength    = hit.distance;

                if (collisions.climbingSlope)
                {
                    //math here: https://www.youtube.com/watch?v=cwcC2tIKObU
                    moveAmount.x = moveAmount.y / Mathf.Tan(collisions.slopeAngle * Mathf.Deg2Rad) * Mathf.Sign(moveAmount.x);
                }

                collisions.below = directionY == -1;
                collisions.above = directionY == 1;
            }
        }
        //chicking for collisions when climbing a slope...?
        if (collisions.climbingSlope)
        {
            float directionX = Mathf.Sign(moveAmount.x);
            rayLength = Mathf.Abs(moveAmount.x) + SKIN_WIDTH;
            Vector2      rayOrigin = ((directionX == -1) ? raycastOrigins.bottomLeft : raycastOrigins.bottomRight) + Vector2.up * moveAmount.y;
            RaycastHit2D hit       = Physics2D.Raycast(rayOrigin, Vector2.right * directionX, rayLength, collisionMask);

            if (hit)
            {
                float slopeAngle = Vector2.Angle(hit.normal, Vector2.up);
                if (slopeAngle != collisions.slopeAngle)
                {
                    moveAmount.x           = (hit.distance - SKIN_WIDTH) * directionX;
                    collisions.slopeAngle  = slopeAngle;
                    collisions.slopeNormal = hit.normal;
                }
            }
        }
    }
コード例 #23
0
ファイル: Unit.cs プロジェクト: Terarrc/Project-Dash
    // Update is called once per frame
    public virtual void Update()
    {
        // Less maneouvrability in the air
        if (isGrounded || verticalMoveEnabled)
        {
            currentAccelerationX = accelerationX;
            currentAccelerationY = accelerationY;
        }
        else
        {
            currentAccelerationX = accelerationX / 2;
            currentAccelerationY = accelerationY / 2;
        }

        float positionX = transform.position.x;
        float positionY = transform.position.y;

        // Update the speed X
        if (currentSpeedX < wantedSpeedX)
        {
            currentSpeedX = Mathf.Min(wantedSpeedX, currentSpeedX + (accelerationX * Time.deltaTime));
        }
        else if (currentSpeedX > wantedSpeedX)
        {
            currentSpeedX = Mathf.Max(wantedSpeedX, currentSpeedX - (accelerationX * Time.deltaTime));
        }

        // Update the speed Y
        if (verticalMoveEnabled)
        {
            if (currentSpeedY < wantedSpeedY)
            {
                currentSpeedY = Mathf.Min(wantedSpeedY, currentSpeedY + (accelerationY * Time.deltaTime));
            }
            else if (currentSpeedY > wantedSpeedY)
            {
                currentSpeedY = Mathf.Max(wantedSpeedY, currentSpeedY - (accelerationY * Time.deltaTime));
            }
        }


        // Update the position X
        if (!Mathf.Approximately(currentSpeedX, 0))
        {
            positionX += currentSpeedX * Time.deltaTime;
        }
        // Update the position Y
        if (verticalMoveEnabled)
        {
            if (!Mathf.Approximately(currentSpeedY, 0))
            {
                positionY += currentSpeedY * Time.deltaTime;
            }
        }

        transform.position = new Vector3(positionX, positionY);

        // Overlap ground check
        // Make a rectangle out of two edges (Vector 2) and if that rectangle overlaps with layer (8) it returns true
        if (boxCollider)
        {
            var hitboxHalf = boxCollider.bounds.size.x / 2;
            isGrounded = Physics2D.OverlapArea(
                new Vector2(transform.position.x - hitboxHalf, transform.position.y),
                new Vector2(transform.position.x + hitboxHalf, transform.position.y - 0.02f), 1 << 8);

            animator.SetBool("Grounded", isGrounded);
        }
        // For animation in the air
        if (body)
        {
            animator.SetFloat("SpeedY", body.velocity.y);
        }
    }
コード例 #24
0
    void HorizontalCollisions(ref Vector2 moveAmount, bool jumpInputDown)
    {
        float directionX = collisions.faceDirection;
        float rayLength  = Mathf.Abs(moveAmount.x) + SKIN_WIDTH;

        //if not moving, check for collisions on the side by a minor amount (usually for wall sliding)
        if (Mathf.Abs(moveAmount.x) < SKIN_WIDTH)
        {
            rayLength = 2 * SKIN_WIDTH;
        }
        //the jumpinputdown variable is for the frame that the player jumps, a ray is not cast from the bottom of the collision, so they won't collide with any slopes and stutter their jump
        //each of the for loops in these sections is to check collissions on each of the rays that are drawn on the colllider
        for (int i = (!jumpInputDown)?0:1; i < horizontalRayCount; i++)
        {
            Vector2 rayOrigin = (directionX == -1) ? raycastOrigins.bottomLeft : raycastOrigins.bottomRight;
            rayOrigin += Vector2.up * (horizontalRaySpacing * i);
            RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.right * directionX, rayLength, collisionMask);

            Debug.DrawRay(rayOrigin, Vector2.right * directionX * rayLength, Color.red);

            if (hit)
            {
                //if hitting a through obstacle from the side, continue (go to the next part of the for loop, in this case, the next ray
                if (hit.collider.tag == "Through")
                {
                    continue;
                }
                //if inside the obstacle, usually in the case of a moving block that pushes you into a solid one
                if (hit.distance == 0)
                {
                    continue;
                }
                //slopes that the user can climb
                float slopeAngle = Vector2.Angle(hit.normal, Vector2.up);
                if (i == 0 && slopeAngle <= maxSlopeAngle)
                {
                    if (collisions.descendingSlope)
                    {
                        collisions.descendingSlope = false;
                        moveAmount = collisions.moveAmountOld;
                    }
                    float distanceToSlopeStart = 0;
                    if (slopeAngle != collisions.slopeAngleOld)
                    {
                        distanceToSlopeStart = hit.distance - SKIN_WIDTH;
                        moveAmount.x        -= distanceToSlopeStart * directionX;
                    }
                    ClimbSlope(ref moveAmount, slopeAngle, hit.normal);
                    moveAmount.x += distanceToSlopeStart * directionX;
                }
                //normal collision
                if (!collisions.climbingSlope || slopeAngle > maxSlopeAngle)
                {
                    moveAmount.x = (hit.distance - SKIN_WIDTH) * directionX;
                    rayLength    = hit.distance;

                    if (collisions.climbingSlope)
                    {
                        //math here: https://www.youtube.com/watch?v=cwcC2tIKObU
                        moveAmount.y = Mathf.Tan(collisions.slopeAngle * Mathf.Deg2Rad) * Mathf.Abs(moveAmount.x);
                    }

                    collisions.left  = directionX == -1;
                    collisions.right = directionX == 1;
                }
            }
        }
    }
コード例 #25
0
	public void Move(float move, bool crouch, bool jump)
	{
		// If crouching, check to see if the character can stand up
		if (!crouch)
		{
			// If the character has a ceiling preventing them from standing up, keep them crouching
			if (Physics2D.OverlapCircle(m_CeilingCheck.position, k_CeilingRadius, m_WhatIsGround))
			{
				crouch = true;
			}
		}

		//only control the player if grounded or airControl is turned on
		if (m_Grounded || m_AirControl)
		{

			// If crouching
			if (crouch)
			{
				if (!m_wasCrouching)
				{
					m_wasCrouching = true;
					OnCrouchEvent.Invoke(true);
				}

				// Reduce the speed by the crouchSpeed multiplier
				move *= m_CrouchSpeed;

				// Disable one of the colliders when crouching
				if (m_CrouchDisableCollider != null)
					m_CrouchDisableCollider.enabled = false;
			}
			else
			{
				// Enable the collider when not crouching
				if (m_CrouchDisableCollider != null)
					m_CrouchDisableCollider.enabled = true;

				if (m_wasCrouching)
				{
					m_wasCrouching = false;
					OnCrouchEvent.Invoke(false);
				}
			}

			// Move the character by finding the target velocity
			Vector3 targetVelocity = new Vector2(move * 10f, m_Rigidbody2D.velocity.y);
			// And then smoothing it out and applying it to the character
			m_Rigidbody2D.velocity = Vector3.SmoothDamp(m_Rigidbody2D.velocity, targetVelocity, ref m_Velocity, m_MovementSmoothing);

			// If the input is moving the player right and the player is facing left...
			if (move > 0 && !m_FacingRight)
			{
				// ... flip the player.
				Flip();
			}
			// Otherwise if the input is moving the player left and the player is facing right...
			else if (move < 0 && m_FacingRight)
			{
				// ... flip the player.
				Flip();
			}
		}
		// If the player should jump...
		if (m_Grounded && jump)
		{
			// Add a vertical force to the player.
			m_Grounded = false;
			m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
		}
	}
コード例 #26
0
        /** Returns if the connection between \a a and \a b is valid.
         * Checks for obstructions using raycasts (if enabled) and checks for height differences.\n
         * As a bonus, it outputs the distance between the nodes too if the connection is valid
         */
        public virtual bool IsValidConnection(GraphNode a, GraphNode b, out float dist)
        {
            dist = 0;

            if (!a.Walkable || !b.Walkable)
            {
                return(false);
            }

            var dir = (Vector3)(b.position - a.position);

            if (
                (!Mathf.Approximately(limits.x, 0) && Mathf.Abs(dir.x) > limits.x) ||
                (!Mathf.Approximately(limits.y, 0) && Mathf.Abs(dir.y) > limits.y) ||
                (!Mathf.Approximately(limits.z, 0) && Mathf.Abs(dir.z) > limits.z))
            {
                return(false);
            }

            dist = dir.magnitude;
            if (maxDistance == 0 || dist < maxDistance)
            {
                if (raycast)
                {
                    var ray       = new Ray((Vector3)a.position, dir);
                    var invertRay = new Ray((Vector3)b.position, -dir);

                    if (use2DPhysics)
                    {
                        if (thickRaycast)
                        {
                            return(!Physics2D.CircleCast(ray.origin, thickRaycastRadius, ray.direction, dist, mask) && !Physics2D.CircleCast(invertRay.origin, thickRaycastRadius, invertRay.direction, dist, mask));
                        }
                        else
                        {
                            return(!Physics2D.Linecast((Vector2)(Vector3)a.position, (Vector2)(Vector3)b.position, mask) && !Physics2D.Linecast((Vector2)(Vector3)b.position, (Vector2)(Vector3)a.position, mask));
                        }
                    }
                    else
                    {
                        if (thickRaycast)
                        {
                            return(!Physics.SphereCast(ray, thickRaycastRadius, dist, mask) && !Physics.SphereCast(invertRay, thickRaycastRadius, dist, mask));
                        }
                        else
                        {
                            return(!Physics.Linecast((Vector3)a.position, (Vector3)b.position, mask) && !Physics.Linecast((Vector3)b.position, (Vector3)a.position, mask));
                        }
                    }
                }
                else
                {
                    return(true);
                }
            }
            return(false);
        }
コード例 #27
0
ファイル: WheelController.cs プロジェクト: J4stMart/WheelGame
    private void CheckGrounded()
    {
        RaycastHit2D hit = Physics2D.BoxCast(groundCheck.bounds.center, groundCheck.bounds.size, 0f, Vector2.down, 0f, collisionMask);

        grounded = hit.collider != null;
    }
コード例 #28
0
    void Update()
    {
        #region KeyboardInput

        if (Application.platform == RuntimePlatform.WindowsEditor ||
            Application.platform == RuntimePlatform.WindowsPlayer)
        {
            if (Input.GetKeyUp(KeyCode.P))
            {
                switch (_isPaused)
                {
                case false:
                    Pause(true);
                    break;

                case true:
                    Pause(false);
                    break;
                }
            }
        }

        #endregion

        #region TouchscreenInput

        if (Application.platform == RuntimePlatform.Android)
        {
            if (Input.touchCount > 0)
            {
                Vector3      touchPosition   = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
                Vector2      touchPosition2D = new Vector2(touchPosition.x, touchPosition.y);
                RaycastHit2D hit             = Physics2D.Raycast(touchPosition2D, Vector2.zero);

                if (hit)
                {
                    if (hit.collider.gameObject.CompareTag("ButtonPause") &&
                        (Input.GetTouch(0).phase == TouchPhase.Ended ||
                         Input.GetTouch(0).phase == TouchPhase.Canceled))
                    {
                        switch (_isPaused)
                        {
                        case false:
                            Pause(true);
                            break;

                        case true:
                            Pause(false);
                            break;
                        }
                    }
                }
            }

            if (Input.GetKeyUp(KeyCode.Escape))
            {
                switch (_isPaused)
                {
                case false:
                    Pause(true);
                    break;

                case true:
                    player.GetComponent <Player>().SaveScore();
                    sceneGameManager.GetComponent <SceneGameManager>().scene = "Main Menu";
                    sceneGameManager.GetComponent <SceneGameManager>().fadeAnimator.SetTrigger("fadeOut");
                    Time.timeScale = 1;
                    break;
                }
            }
        }

        #endregion
    }
コード例 #29
0
    public void ActionHandler()
    {
        if (state == States.None)
        {
            if (IsMouseButtonPressed() && GetClickedObject().name != ".")
            {
                PickUp();
                Debug.Log(item.name);
            }
        }
        else
        {
            if (IsMouseButtonPressed())
            {
                Drag();
            }
            else
            {
                Drop();
            }
        }

        bool IsMouseButtonPressed()
        {
            return(Input.GetMouseButton(0));
        }

        void Drop()
        {
            toPosition = item.transform.position;
            DropObject(fromPosition, toPosition);
            item  = null;
            state = States.None;
        }

        void Drag()
        {
            item.transform.position = GetClickPosition();
        }

        void PickUp()
        {
            Vector2   clickPosition = GetClickPosition();
            Transform clickedItem   = GetItemAt(clickPosition);

            if (clickedItem == null)
            {
                return;
            }
            state        = States.Drag;
            item         = clickedItem.gameObject;
            fromPosition = clickedItem.position;
            offset       = fromPosition - clickPosition;
            PickObject(fromPosition);
        }

        Vector2 GetClickPosition()
        {
            return(Camera.main.ScreenToWorldPoint(Input.mousePosition));
        }

        Transform GetItemAt(Vector2 position)
        {
            RaycastHit2D[] figures = Physics2D.RaycastAll(position, position, 0.5f);
            if (figures.Length == 0)
            {
                return(null);
            }
            return(figures[0].transform);
        }

        GameObject GetClickedObject()
        {
            Vector2   clickPosition = GetClickPosition();
            Transform clickedItem   = GetItemAt(clickPosition);

            return(clickedItem.gameObject);
        }
    }
コード例 #30
0
 private bool IsWithinReach(Vector2 pos, Vector2 damageablePos, float distance)
 {
     return(distance <= radius && Physics2D.Raycast(pos, damageablePos - pos, distance, OBSTACLE_MASK).collider == null);
 }