Example #1
0
 // Internal
 protected void UpdateGrounded()
 {
     IsGrounded = (Physics2D.BoxCast(col.bounds.center, col.bounds.size, 0f, Vector2.down, groundCheckDistance, groundLayer.value).collider != null);
     //IsGrounded = (Physics2D.CapsuleCast(col.bounds.center, col.size, col.direction, 0f, Vector2.down, groundCheckDistance, groundLayer.value).collider != null);
     anim.SetBool(groundedParameterHash, IsGrounded);
 }
Example #2
0
    bool IsGrounded()
    {
        RaycastHit2D raycastHit2d = Physics2D.BoxCast(boxCollider2d.bounds.center, boxCollider2d.bounds.size, 0f, Vector2.down, .1f, platformLayerMask);

        return(raycastHit2d.collider != null);
    }
Example #3
0
    /// 检测下一帧的位置是否能够移动,并进行修正
    public void CheckNextMove()
    {
        Vector3 moveDistance = moveSpeed * Time.deltaTime;
        int     dir          = 0;//确定下一帧移动的左右方向

        if (moveSpeed.x > 0)
        {
            dir = 1;
        }
        else if (moveSpeed.x < 0)
        {
            dir = -1;
        }
        else
        {
            dir = 0;
        }
        if (dir != 0)//当左右速度有值时
        {
            RaycastHit2D lRHit2D = Physics2D.BoxCast(transform.position, boxSize, 0, Vector2.right * dir, 5.0f, playerLayerMask);
            if (lRHit2D.collider != null)                                                    //如果当前方向上有碰撞体
            {
                float   tempXVaule    = (float)Math.Round(lRHit2D.point.x, 1);               //取X轴方向的数值,并保留1位小数精度。防止由于精度产生鬼畜行为
                Vector3 colliderPoint = new Vector3(tempXVaule, transform.position.y);       //重新构建射线的碰撞点
                float   tempDistance  = Vector3.Distance(colliderPoint, transform.position); //计算玩家与碰撞点的位置
                if (tempDistance > (boxSize.x * 0.5f + distance))                            //如果距离大于 碰撞盒子的高度的一半+最小地面距离
                {
                    transform.position += new Vector3(moveDistance.x, 0, 0);
                    if (isClimb)        //如果左右方向没有碰撞体了,退出爬墙状态
                    {
                        isClimb = false;
                        playAnimator.ResetTrigger("IsClimb"); //重置触发器  退出
                        playAnimator.SetTrigger("exitClimp");
                    }
                }
                else//如果距离小于  根据方向进行位移修正
                {
                    float tempX = 0;//新的X轴的位置
                    if (dir > 0)
                    {
                        tempX = tempXVaule - boxSize.x * 0.5f - distance + 0.01f;
                    }
                    else
                    {
                        tempX = tempXVaule + boxSize.x * 0.5f + distance - 0.01f;
                    }
                    if (lRHit2D.collider.CompareTag("Monster"))
                    {
                        Die();
                    }
                    transform.position = new Vector3(tempX, transform.position.y, 0); //修改玩家的位置
                    if (!lRHit2D.collider.CompareTag("Trap"))                         //如果左右不是陷阱
                    {
                        EnterClimpFunc(transform.position);                           //检测当前是否能够进入爬墙状态
                        playAnimator.ResetTrigger("exitClimp");
                    }
                    else
                    {
                        Die();
                    }
                }
            }
            else
            {
                transform.position += new Vector3(moveDistance.x, 0, 0);
                if (isClimb)
                {
                    isClimb = false;
                    playAnimator.SetTrigger("exitClimp");
                    playAnimator.ResetTrigger("IsClimb"); //重置触发器  退出
                }
            }
        }
        //更新方向信息,上下轴
        if (moveSpeed.y > 0)
        {
            dir = 1;
        }
        else if (moveSpeed.y < 0)
        {
            dir = -1;
        }
        else
        {
            dir = 0;
        }
        //上下方向进行判断
        if (dir != 0)
        {
            RaycastHit2D uDHit2D = Physics2D.BoxCast(transform.position, boxSize, 0, Vector3.up * dir, 5.0f, playerLayerMask);
            if (uDHit2D.collider != null)
            {
                float   tempYVaule    = (float)Math.Round(uDHit2D.point.y, 1);
                Vector3 colliderPoint = new Vector3(transform.position.x, tempYVaule);
                float   tempDistance  = Vector3.Distance(transform.position, colliderPoint);

                if (tempDistance > (boxSize.y * 0.5f + distance))
                {
                    float tempY = 0;
                    float nextY = transform.position.y + moveDistance.y;
                    if (dir > 0)
                    {
                        tempY = tempYVaule - boxSize.y * 0.5f - distance;
                        if (nextY > tempY)
                        {
                            transform.position = new Vector3(transform.position.x, tempY + 0.1f, 0);
                        }
                        else
                        {
                            transform.position += new Vector3(0, moveDistance.y, 0);
                        }
                    }
                    else
                    {
                        tempY = tempYVaule + boxSize.y * 0.5f + distance;
                        if (nextY < tempY)
                        {
                            transform.position = new Vector3(transform.position.x, tempY - 0.1f, 0);
                        }
                        else
                        {
                            transform.position += new Vector3(0, moveDistance.y, 0);
                        }
                    }
                    isGround = false;   //更新在地面的bool值
                }
                else
                {
                    float tempY = 0;
                    if (dir > 0)//如果是朝上方向移动,且距离小于规定距离,就说明玩家头上碰到了物体,反之同理。
                    {
                        tempY    = uDHit2D.point.y - boxSize.y * 0.5f - distance + 0.05f;
                        isGround = false;
                    }
                    else
                    {
                        tempY    = uDHit2D.point.y + boxSize.y * 0.5f + distance - 0.05f;
                        isGround = true;
                    }
                    moveSpeed.y        = 0;
                    transform.position = new Vector3(transform.position.x, tempY, 0);
                    if (uDHit2D.collider.CompareTag("Monster"))
                    {
                        Die();
                    }
                    if (uDHit2D.collider.CompareTag("Trap"))
                    {
                        Die();
                    }
                }
            }
            else
            {
                isGround            = false;
                transform.position += new Vector3(0, moveDistance.y, 0);
            }
        }
        else
        {
            isGround = CheckIsGround();//更新在地面的bool值
        }
    }
Example #4
0
 private bool CheckHitBox(Vector2 direction)
 {
     return(Physics2D.BoxCast(_hitbox.bounds.center, new Vector2(0.1f, 0.1f), 0f, direction, 0.1f, _floorLayerMask) ||
            Physics2D.BoxCast(_hitbox.bounds.center, new Vector2(0.1f, 0.1f), 0f, direction, 0.1f, _platformLayerMask));
 }
    void FixedUpdate()
    {
        GetRelativePosition();

        SeparateEnvironment();

        CheckGround();

        // UPDATE SPEED
        if (isGrounded)
        {
            if (goLeft)
            {
                velocity = new Vector2(-speed, 0);
            }
            else if (goRight)
            {
                velocity = new Vector2(speed, 0);
            }
            else
            {
                velocity = Vector2.zero;
            }

            if (jump)
            {
                velocity += jumpSpeed * Vector2.up;
                jump      = false;
            }
        }
        else
        {
            if (goLeft)
            {
                velocity += new Vector2(-midAirForce, 0) * Time.fixedDeltaTime;
            }
            else if (goRight)
            {
                velocity += new Vector2(midAirForce, 0) * Time.fixedDeltaTime;
            }

            velocity += Physics2D.gravity * Time.fixedDeltaTime;
        }

        Vector3 velocityUnit = velocity.normalized;
        float   distance     = velocity.magnitude * Time.fixedDeltaTime;

        RaycastHit2D hit = Physics2D.BoxCast(transform.position, bounds, 0, velocityUnit, distance);

        if (hit)
        {
            transform.position += velocityUnit * Mathf.Min(distance, Vector2.Dot(((Vector3)hit.point - transform.position), velocityUnit));
        }
        else
        {
            transform.position += velocityUnit * distance;
        }

        SeparateEnvironment();

        SetRelativePosition();
    }
Example #6
0
    // Update is called once per frame
    void FixedUpdate()
    {
        float deltaTime = Time.fixedDeltaTime;

        if (m_locations.Length <= 1)
        {
            return;
        }

        m_time += deltaTime * m_speed / m_locations.Length;

        while (m_time >= 1.0f)
        {
            m_time -= 1.0f;
            index++;
            if (index == m_locations.Length)
            {
                index = 0;
            }
        }

        uint next = index + 1;

        if (next == m_locations.Length)
        {
            next = 0;
        }

        float time;

        switch (m_interpolation)
        {
        case EInterpotionType.Cubic:
            time = EaseInOutCubic(m_time);
            break;

        case EInterpotionType.Quadratic:
            time = EaseInOutQuad(m_time);
            break;

        default:
            time = m_time;
            break;
        }

        Vector2 position      = transform.position;
        Vector2 newPosition   = Vector2.Lerp(m_locations [index].position, m_locations [next].position, time);
        Vector2 collisionPos  = position + m_offset;
        Vector2 localVelocity = newPosition - position;

        RaycastHit2D hit2D = Physics2D.BoxCast(collisionPos, m_size, 0, localVelocity.normalized, localVelocity.magnitude + 0.01f);

        if (hit2D && hit2D.transform.parent != transform && (!m_oneWay || localVelocity.y >= 0))
        {
            Vector3 newPos = localVelocity;            // - (hit2D.normal * 0.01f);
            hit2D.transform.position += newPos;
            // Debug.Log(Time.frameCount + "push" + hit2D.transform.name);
        }

        transform.position = newPosition;

        DebugDraw();
    }
Example #7
0
    void Update()
    {
        if (Input.touchCount > 0)
        {
            Touch   touch         = Input.GetTouch(0);
            Vector2 touchPosition = touch.position;
            Vector3 wp            = Camera.main.ScreenToWorldPoint(touchPosition);
            wp.z = 0;

            RaycastHit2D hit = Physics2D.BoxCast(wp, Vector2.one * 0.1f, 0f, Vector2.zero);

            if (hit)
            {
                Debug.Log(hit.transform.name);
            }

            if (touch.phase == TouchPhase.Began)
            {
                //If we just started pressing (1 frame when user clicked)
                if (hit && !IsPointerOverUIObject())
                {
                    hitObjectOnStart        = hit.transform.gameObject;
                    hitAndObjectCenterDelta = hit.transform.position - Camera.main.ScreenToWorldPoint(touchPosition);

                    if (focusedObject && focusedObject == hit.transform.gameObject)
                    {
                        isHitOnFocusedObject = true;
                    }
                    else
                    {
                        isHitOnFocusedObject = false;
                    }
                }
                else
                {
                    hitObjectOnStart        = null;
                    isHitOnFocusedObject    = false;
                    hitAndObjectCenterDelta = Vector2.zero;
                }

                startTime = Time.time;
            }
            else if (touch.phase == TouchPhase.Ended)
            {
                //If we just ended pressing (1 frame when user releasd his finger)
                if (Time.time - startTime < 0.1f && hit && hitObjectOnStart == hit.transform.gameObject)
                {
                    if (IsNowAddingRigidLink)
                    {
                        bool ok = true;
                        foreach (NonPhysicalJoint j in focusedObject.GetComponents <NonPhysicalJoint>())
                        {
                            if (j.connectedObject == hitObjectOnStart)
                            {
                                ok = false;
                                DisplayError("A joint was already added to this object");
                            }
                        }
                        foreach (NonPhysicalJoint j in hitObjectOnStart.GetComponents <NonPhysicalJoint>())
                        {
                            if (j.connectedObject == focusedObject)
                            {
                                ok = false;
                                DisplayError("A joint was already added to this object");
                            }
                        }
                        if (focusedObject == hitObjectOnStart)
                        {
                            ok = false;
                            DisplayError("You cannot attach an object to itself");
                        }
                        if (ok)
                        {
                            NonPhysicalJoint joint = focusedObject.AddComponent <NonPhysicalJoint>();
                            joint.IsHingedJoint = false;
                            joint.SetConnectedObject(hit.transform.gameObject);
                            if (isPausedNow)
                            {
                                joint.Pause();
                            }
                            else
                            {
                                joint.Unpause();
                            }

                            LineBetweenTwoObjects liner = Instantiate(linerPrefab, Vector3.zero, Quaternion.identity).GetComponent <LineBetweenTwoObjects>();
                            liner.materialToSet = linerFixedMaterial;
                            liner.object1       = hit.transform.gameObject;
                            liner.attachedJoint = joint;
                            liner.object2       = focusedObject;
                        }


                        hitObjectOnStart        = null;
                        IsNowAddingRigidLink    = false;
                        hitAndObjectCenterDelta = Vector2.zero;
                        startTime = 0f;
                        addingJointImage.GetComponent <Animation>().Play("NowAddingPanelSlideOut");
                    }
                    else if (IsNowAddingHingedLink)
                    {
                        bool ok = true;
                        foreach (NonPhysicalJoint j in focusedObject.GetComponents <NonPhysicalJoint>())
                        {
                            if (j.connectedObject == hitObjectOnStart)
                            {
                                ok = false;
                                DisplayError("A joint was already added to this object");
                            }
                        }
                        foreach (NonPhysicalJoint j in hitObjectOnStart.GetComponents <NonPhysicalJoint>())
                        {
                            if (j.connectedObject == focusedObject)
                            {
                                ok = false;
                                DisplayError("A joint was already added to this object");
                            }
                        }
                        if (ok)
                        {
                            if (focusedObject == hitObjectOnStart)
                            {
                                ok = false;
                                DisplayError("You cannot attach an object to itself");
                            }

                            NonPhysicalJoint joint = focusedObject.AddComponent <NonPhysicalJoint>();
                            joint.SetConnectedObject(hit.transform.gameObject);
                            joint.IsHingedJoint = true;
                            if (isPausedNow)
                            {
                                joint.Pause();
                            }
                            else
                            {
                                joint.Unpause();
                            }

                            LineBetweenTwoObjects liner = Instantiate(linerPrefab, Vector3.zero, Quaternion.identity).GetComponent <LineBetweenTwoObjects>();
                            liner.materialToSet = linerHingedMaterial;
                            liner.object1       = hit.transform.gameObject;
                            liner.attachedJoint = joint;
                            liner.object2       = focusedObject;
                        }

                        hitObjectOnStart        = null;
                        IsNowAddingHingedLink   = false;
                        hitAndObjectCenterDelta = Vector2.zero;
                        startTime = 0f;
                        addingJointImage.GetComponent <Animation>().Play("NowAddingPanelSlideOut");
                    }
                    else
                    {
                        hitObjectOnStart = null;
                        SetObjectAsFocused(hit.transform.gameObject);
                        hitAndObjectCenterDelta = Vector2.zero;
                        startTime = 0f;
                    }
                }
                isHitOnFocusedObject = false;

                AllowCameraMovement = true;
            }
            else
            {
                //If we are moving our finger
                if (isHitOnFocusedObject)
                {
                    Vector3 worldPos = Camera.main.ScreenToWorldPoint(touchPosition);
                    worldPos.z = 0;

                    /*bool pivoted = false;
                     * foreach (GameObject pivot in pivotPoints)
                     * {
                     *      //Debug.Log((pivot.transform.position - worldPos).magnitude);
                     *      if (pivot != focusedObject && (pivot.transform.position - worldPos).magnitude < 0.5f && pivot.GetComponent<ExportObjectData>().hingedObject == null)
                     *      {
                     *              pivot.GetComponent<ExportObjectData>().hingedObject = focusedObject;
                     *              focusedObject.GetComponent<ExportObjectData>().hingedObject = focusedObject;
                     *              pivoted = true;
                     *              worldPos = pivot.transform.position + (Vector3)hitAndObjectCenterDelta;
                     *              break;
                     *      }
                     * }*/
                    worldPos += (Vector3)hitAndObjectCenterDelta;
                    RoundVector(ref worldPos);
                    worldPos.z = 0;
                    focusedObject.transform.position = worldPos;
                    AllowCameraMovement = false;
                }
            }
        }

        if (AllowCameraMovement && !IsPointerOverUIObject())
        {
            controller.UpdateCamera();
        }

        if (focusedObject == null)
        {
            linkHingeButton.interactable = false;
            linkFixedButton.interactable = false;
            deleteButton.interactable    = false;
            rotateCCWButton.interactable = false;
            rotateCWButton.interactable  = false;
        }
        else
        {
            linkHingeButton.interactable = true;
            linkFixedButton.interactable = true;
            deleteButton.interactable    = true;
            rotateCCWButton.interactable = true;
            rotateCWButton.interactable  = true;
        }

        if (focusedObjectData != null && focusedObjectData.isMotorPort)
        {
            for (int i = 0; i < 8; i++)
            {
                if (brainData.connectedMotors[i] == null)
                {
                    portCheckboxList[i].interactable = true;
                    portCheckboxList[i].isOn         = false;
                }
                else if (i == focusedObjectData.connectedPort)
                {
                    portCheckboxList[i].interactable = true;
                    portCheckboxList[i].isOn         = true;
                }
                else
                {
                    portCheckboxList[i].interactable = false;
                    portCheckboxList[i].isOn         = false;
                }
            }
        }
        else if (focusedObjectData != null && focusedObjectData.isSensorPort)
        {
            for (int i = 0; i < 8; i++)
            {
                if (brainData.connectedSensors[i] == null)
                {
                    portCheckboxList[i].interactable = true;
                    portCheckboxList[i].isOn         = false;
                }
                else if (i == focusedObjectData.connectedPort)

                {
                    portCheckboxList[i].interactable = true;
                    portCheckboxList[i].isOn         = true;
                }
                else
                {
                    portCheckboxList[i].interactable = false;
                    portCheckboxList[i].isOn         = false;
                }
            }
        }
    }
Example #8
0
    //code from Tom Tsiliopoulos "In class"
    void Move()
    {
        //Checking if the Enemy is on ground or midair
        isGrounded = Physics2D.BoxCast(
            transform.position,
            new Vector2(2.0f, 1.0f),
            0.0f,
            Vector2.down,
            1.0f,
            1 << LayerMask.NameToLayer("Ground"));


        //Stop
        if (Input.GetAxis("Horizontal") == 0 && isGrounded)
        {
            playerAnimState = PlayerAnimState.IDLE;
            playerAnimator.SetInteger("AnimState", (int)PlayerAnimState.IDLE);
        }

        //Right
        if (Input.GetAxis("Horizontal") > 0)
        {
            playerSpriteRenderer.flipX = true;
            playerAnimState            = PlayerAnimState.WALK;
            playerAnimator.SetInteger("AnimState", (int)PlayerAnimState.WALK);
            playerRigidBody.AddForce(Vector2.right * moveForce);
        }

        //Left
        if (Input.GetAxis("Horizontal") < 0)
        {
            playerSpriteRenderer.flipX = false;
            playerAnimState            = PlayerAnimState.WALK;
            playerAnimator.SetInteger("AnimState", (int)PlayerAnimState.WALK);
            playerRigidBody.AddForce(Vector2.left * moveForce);
        }

        //Jump
        if (Input.GetAxis("Jump") > 0 && isGrounded)
        {
            playerAnimState = PlayerAnimState.JUMP;
            playerAnimator.SetInteger("AnimState", (int)PlayerAnimState.JUMP);
            playerRigidBody.AddForce(Vector2.up * jumpForce);
            isGrounded = false;
        }

        //Midair
        if (!isGrounded)
        {
            playerAnimState = PlayerAnimState.JUMP;
        }

        //Jump Sound
        if (Input.GetButtonDown("Jump"))
        {
            jumpSound.Play();
        }

        //Restricts maximum velocity to certain amount
        playerRigidBody.velocity = new Vector2(
            Mathf.Clamp(playerRigidBody.velocity.x, -maximumVelocity.x, maximumVelocity.x),
            Mathf.Clamp(playerRigidBody.velocity.y, -maximumVelocity.y, maximumVelocity.y)
            );
    }
Example #9
0
    private void Update()
    {
        time      += Time.deltaTime;
        boss_time += Time.deltaTime;
        #region [죽음의 사자]
        if (this_type == Boss_Type.Death)
        {
            if (boss_time <= 5)
            {
                starty = transform.position.y;
            }
            #region [보스죽음]
            if (!animator.GetBool("Death") && animator.GetInteger("Pattern") != 44)
            {
                animator.SetBool("Death", GameManager.Boss_now_hp <= 0 ? true : false);
            }
            if (animator.GetInteger("Pattern") == 44)
            {
                animator.SetBool("Death", false);
            }
            if (animator.GetCurrentAnimatorStateInfo(0).IsName("Demon_Death"))
            {
                StageManager.player_static.GetComponent <Player_Maker>().stop = true;
                deathtime += Time.deltaTime;
                GetComponent <Rigidbody2D>().velocity = Vector2.zero;
                if (deathtime >= 3f)
                {
                    Camera_Maker[] cam = StageManager.camera_static.GetComponents <Camera_Maker>();
                    try
                    {
                        cam[1].enabled = false;
                        cam[2].enabled = true;
                    }
                    catch { Debug.Log("1번이나 , 2번카메라 없음"); }
                    if (GameManager.Boss_UI)
                    {
                        GameManager.Boss_UI.SetActive(false);
                    }

                    StageManager.player_static.GetComponent <Player_Maker>().stop = false;
                    animator.SetInteger("Pattern", 44);
                }
                if (time > 0.25f)
                {
                    EffectManager.Play_Boom(transform.position + new Vector3(Random.Range(-0.5f, +0.5f), Random.Range(-0.5f, +0.5f), 0), 0);
                    time = 0;
                }
            }
            if (animator.GetCurrentAnimatorStateInfo(0).IsName("Demon_Death_End"))
            {
                Destroy(gameObject);
            }
            if (GameManager.Boss_UI && GameManager.Boss_now_hp <= 0)
            {
                return;
            }
            #endregion

            #region [보스패턴]
            if (time > 3f / animator.speed)
            {
                animator.speed = (GameManager.GameLevel == TutorialScript.GameLevel.쉬움) ? 0.75f : (GameManager.Boss_now_hp > GameManager.Boss_max_hp * 0.5f && GameManager.GameLevel == TutorialScript.GameLevel.보통) ? 0.75f : 1.25f;
                if (pattern == -1)
                {
                    int r = 0;
                    if (boss_time > 10f)
                    {
                        if ((GameManager.Boss_now_hp > GameManager.Boss_max_hp * 0.5f && GameManager.GameLevel == TutorialScript.GameLevel.보통) || GameManager.GameLevel == TutorialScript.GameLevel.쉬움)
                        {
                            do
                            {
                                r = Random.Range(0, 4);
                            } while (backpattern == r);
                        }
                        else
                        {
                            do
                            {
                                r = Random.Range(0, 5);
                            } while (backpattern == r);
                        }
                    }
                    pattern = r;
                }
                if (pattern == 0 || pattern == 1 || pattern == 2)
                {
                    #region [패턴1]
                    if (animator.GetCurrentAnimatorStateInfo(0).IsName("Demon_Pattern0"))
                    {
                        if (animator.GetCurrentAnimatorStateInfo(0).normalizedTime >= 1f)
                        {
                            time    = 0;
                            pattern = -1;
                            animator.SetInteger("Pattern", -1);
                            GetComponent <Rigidbody2D>().velocity = GetComponent <Rigidbody2D>().velocity * 2 * animator.speed;
                        }
                        else if (animator.GetCurrentAnimatorStateInfo(0).normalizedTime >= 0.55f)
                        {
                            GetComponent <Rigidbody2D>().velocity = transform.lossyScale.x == -1 ? new Vector2(2f * animator.speed, GetComponent <Rigidbody2D>().velocity.y) : new Vector2(-2f, GetComponent <Rigidbody2D>().velocity.y);
                        }
                        else
                        {
                            GetComponent <Rigidbody2D>().velocity = Vector2.zero;
                            GameManager.VibrationCamera(0.1f);
                        }
                    }
                    else
                    {
                        if (Vector2.Distance(transform.position, StageManager.player_static.transform.position) <= 2f)
                        {
                            animator.SetInteger("Pattern", 1);
                            SoundManager.ExplosionSE(true);
                        }
                        else
                        {
                            backpattern          = pattern;
                            transform.localScale = transform.position.x > StageManager.player_static.transform.position.x ? new Vector3(+1, 1, 1) : transform.position.x < StageManager.player_static.transform.position.x ? new Vector3(-1, 1, 1) : transform.localScale;
                            GetComponent <Rigidbody2D>().velocity = transform.lossyScale.x == -1 ? new Vector2(4f * animator.speed, GetComponent <Rigidbody2D>().velocity.y) : new Vector2(-4f * animator.speed, GetComponent <Rigidbody2D>().velocity.y);
                        }
                    }
                }
                #endregion
                else if (pattern == 3 || pattern == 4)
                {
                    #region [패턴2]
                    if (animator.GetCurrentAnimatorStateInfo(0).IsName("Demon_Pattern1"))
                    {
                        if (transform.position.y > StageManager.camera_static.transform.position.y + StageManager.camera_static.GetComponent <Camera>().orthographicSize * 2)
                        {
                            GetComponent <Rigidbody2D>().velocity = new Vector2(0, 0);
                            fireball_time += Time.deltaTime;
                            if (fireball_time > 1 / animator.speed)
                            {
                                GameObject emp = Instantiate(fire_ball_prefab, transform.position, Quaternion.identity);
                                Vector3    dic = StageManager.player_static.transform.position - emp.transform.position;
                                dic = dic.normalized;
                                emp.GetComponent <Rigidbody2D>().AddForce(dic * 0.03f * animator.speed);
                                fireball_time = 0;
                                fireballcount++;
                            }
                            if (fireballcount > 3 * animator.speed)
                            {
                                time          = 0;
                                pattern       = -1;
                                fireballcount = 0;
                                fireball_time = 0;
                                animator.SetInteger("Pattern", -1);

                                transform.position = new Vector3(StageManager.camera_static.transform.position.x, starty, transform.position.z) + (Random.Range(0, 100) > 50 ? +3 : -3) * new Vector3(StageManager.camera_static.GetComponent <Camera>().orthographicSize, 0, 0);
                                SoundManager.ExplosionSE(true);
                            }
                        }
                        else
                        {
                            GetComponent <Rigidbody2D>().velocity = new Vector2(0, 2 * animator.speed);
                        }
                    }
                    else
                    {
                        backpattern = pattern;
                        animator.SetInteger("Pattern", 2);
                        transform.position   = new Vector3(StageManager.camera_static.transform.position.x, StageManager.camera_static.transform.position.y - StageManager.camera_static.GetComponent <Camera>().orthographicSize, transform.position.z);
                        transform.localScale = new Vector3(0.5f, 0.5f, 1);
                    }
                    #endregion
                }
            }
            #endregion
        }
        #endregion

        #region [소환사]
        else if (this_type == Boss_Type.Summoner)
        {
            #region [보스죽음]
            if (!animator.GetBool("Death") && animator.GetInteger("Pattern") != 44)
            {
                animator.SetBool("Death", GameManager.Boss_now_hp <= 0 ? true : false);
            }
            if (animator.GetInteger("Pattern") == 44)
            {
                animator.SetBool("Death", false);
            }
            if (animator.GetCurrentAnimatorStateInfo(0).IsName("Summoner_Death"))
            {
                animator.SetBool("Death", false);
                StageManager.player_static.GetComponent <Player_Maker>().stop = true;
                deathtime += Time.deltaTime;
                GetComponent <Rigidbody2D>().velocity = Vector2.zero;
                if (deathtime >= 3f)
                {
                    Camera_Maker[] cam = StageManager.camera_static.GetComponents <Camera_Maker>();
                    try
                    {
                        cam[1].enabled = false;
                        cam[0].enabled = true;
                    }
                    catch { Debug.Log("0번이나 , 1번카메라 없음"); }
                    if (GameManager.Boss_UI)
                    {
                        GameManager.Boss_UI.SetActive(false);
                    }

                    StageManager.player_static.GetComponent <Player_Maker>().stop = false;
                    animator.SetInteger("Pattern", 44);
                }
                if (time > 0.25f)
                {
                    EffectManager.Play_Boom(transform.position + new Vector3(Random.Range(-0.2f, +0.2f), Random.Range(-0.3f, +0.3f), 0), 0);
                    time = 0;
                }
            }
            if (animator.GetCurrentAnimatorStateInfo(0).IsName("Summoner_Death_End"))
            {
                Destroy(gameObject);
            }
            if (GameManager.Boss_UI && GameManager.Boss_now_hp <= 0)
            {
                return;
            }
            #endregion

            #region [보스패턴]
            if (animator.GetCurrentAnimatorStateInfo(0).IsName("Summoner") && boss_time > 6f)
            {
                if (StageManager.camera_static.transform.position.x + StageManager.camera_static.GetComponent <Camera>().orthographicSize < transform.position.x)
                {
                    speed = -speed;
                    GetComponent <SpriteRenderer>().flipX = !GetComponent <SpriteRenderer>().flipX;
                }
                else if (StageManager.camera_static.transform.position.x - StageManager.camera_static.GetComponent <Camera>().orthographicSize > transform.position.x)
                {
                    speed = -speed;
                    GetComponent <SpriteRenderer>().flipX = !GetComponent <SpriteRenderer>().flipX;
                }
            }
            if (boss_time > 6f)
            {
                turn_time += Time.deltaTime;
                if (turn_time > 0.5f)
                {
                    move_speed = -move_speed;
                    turn_time  = 0;
                }
                if (pattern == -1)
                {
                    GetComponent <Rigidbody2D>().velocity = new Vector2(speed, move_speed);
                }
                else
                {
                    GetComponent <Rigidbody2D>().velocity = new Vector2(0, 0);
                }
            }
            if (time > 3f / animator.speed)
            {
                animator.speed = (GameManager.GameLevel == TutorialScript.GameLevel.쉬움) ? 0.75f : (GameManager.Boss_now_hp > GameManager.Boss_max_hp * 0.5f && GameManager.GameLevel == TutorialScript.GameLevel.보통) ? 0.75f : 1.25f;
                if (pattern == -1)
                {
                    int r = 0;
                    if (boss_time > 6f)
                    {
                        if ((GameManager.Boss_now_hp > GameManager.Boss_max_hp * 0.5f && GameManager.GameLevel == TutorialScript.GameLevel.보통) || GameManager.GameLevel == TutorialScript.GameLevel.쉬움)
                        {
                            do
                            {
                                r = Random.Range(0, 4);
                            } while (backpattern == r);
                        }
                        else
                        {
                            do
                            {
                                r = Random.Range(0, 5);
                            } while (backpattern == r);
                        }
                    }
                    pattern = r;
                }
                if (pattern == 0 || pattern == 1 || pattern == 2)
                {
                    #region [패턴1]
                    if (animator.GetInteger("Pattern") != 1)
                    {
                        animator.SetInteger("Pattern", 1);
                    }
                    if (animator.GetCurrentAnimatorStateInfo(0).IsName("Summoner_Pattern0"))
                    {
                        if (animator.GetCurrentAnimatorStateInfo(0).normalizedTime % 1 >= 0.8f && !patterncheck)
                        {
                            fireballcount++;
                            patterncheck = true;
                        }
                        else if (animator.GetCurrentAnimatorStateInfo(0).normalizedTime % 1 >= 0.99f && patterncheck)
                        {
                            patterncheck = false;
                        }
                        if (fireballcount > 3)
                        {
                            patterncheck  = false;
                            fireballcount = 0;
                            time          = 0;
                            pattern       = -1;
                            animator.SetInteger("Pattern", -1);
                            GetComponent <Rigidbody2D>().velocity = GetComponent <Rigidbody2D>().velocity * 2 * animator.speed;
                        }
                    }
                    #endregion
                }
                else if (pattern == 3 || pattern == 4)
                {
                    #region [패턴2]
                    if (animator.GetInteger("Pattern") != 2)
                    {
                        animator.SetInteger("Pattern", 2);
                    }
                    if (animator.GetCurrentAnimatorStateInfo(0).IsName("Summoner_Pattern1"))
                    {
                        if (transform.position.y > StageManager.camera_static.transform.position.y + StageManager.camera_static.GetComponent <Camera>().orthographicSize * 2)
                        {
                            GetComponent <Rigidbody2D>().velocity = new Vector2(0, 0);
                            fireball_time += Time.deltaTime;
                            if (fireball_time > 1 / animator.speed)
                            {
                                /*
                                 * GameObject emp = Instantiate(fire_ball_prefab, transform.position, Quaternion.identity);
                                 * Vector3 dic = StageManager.player_static.transform.position - emp.transform.position;
                                 * dic = dic.normalized;
                                 * emp.GetComponent<Rigidbody2D>().AddForce(dic * 0.03f * animator.speed);
                                 * fireball_time = 0;
                                 * fireballcount++;
                                 */
                            }
                            if (fireballcount > 3 * animator.speed)
                            {
                                /*
                                 * time = 0;
                                 * pattern = -1;
                                 * fireballcount = 0;
                                 * fireball_time = 0;
                                 * animator.SetInteger("Pattern", -1);
                                 *
                                 * transform.position = new Vector3(StageManager.camera_static.transform.position.x, starty, transform.position.z) + (Random.Range(0, 100) > 50 ? +3 : -3) * new Vector3(StageManager.camera_static.GetComponent<Camera>().orthographicSize, 0, 0);
                                 * SoundManager.ExplosionSE(true);
                                 */
                            }
                        }
                        else
                        {
                            // GetComponent<Rigidbody2D>().velocity = new Vector2(0, 2 * animator.speed);
                        }
                    }
                    else
                    {
                        backpattern = pattern;
                        animator.SetInteger("Pattern", 2);
                    }
                    #endregion
                }
            }
            #endregion
        }
        #endregion

        #region [슬라임]
        else if (this_type == Boss_Type.Slime)
        {
            #region [보스죽음]
            if (!animator.GetBool("Death") && animator.GetInteger("Pattern") != 44)
            {
                animator.SetBool("Death", GameManager.Boss_now_hp <= 0 ? true : false);
            }
            if (animator.GetInteger("Pattern") == 44)
            {
                animator.SetBool("Death", false);
            }
            if (animator.GetCurrentAnimatorStateInfo(0).IsName("Slime_Death"))
            {
                animator.SetBool("Death", false);
                StageManager.player_static.GetComponent <Player_Maker>().stop = true;
                deathtime += Time.deltaTime;
                GetComponent <Rigidbody2D>().velocity = Vector2.zero;
                if (deathtime >= 3f)
                {
                    Camera_Maker[] cam = StageManager.camera_static.GetComponents <Camera_Maker>();
                    try
                    {
                        cam[1].enabled = false;
                        cam[0].enabled = true;
                    }
                    catch { Debug.Log("0번이나 , 1번카메라 없음"); }
                    if (GameManager.Boss_UI)
                    {
                        GameManager.Boss_UI.SetActive(false);
                    }

                    StageManager.player_static.GetComponent <Player_Maker>().stop = false;
                    animator.SetInteger("Pattern", 44);
                }
                if (time > 0.25f)
                {
                    EffectManager.Play_Boom(transform.position + new Vector3(Random.Range(-0.2f, +0.2f), Random.Range(-0.3f, +0.3f), 0), 0);
                    time = 0;
                }
            }
            if (animator.GetCurrentAnimatorStateInfo(0).IsName("Slime_Death_End"))
            {
                Destroy(gameObject);
            }
            if (GameManager.Boss_UI && GameManager.Boss_now_hp <= 0)
            {
                return;
            }
            #endregion
            BoxCollider2D  boxCollider2D  = GetComponent <BoxCollider2D>();
            SpriteRenderer spriteRenderer = GetComponent <SpriteRenderer>();
            RaycastHit2D   hit            = Physics2D.BoxCast(new Vector2(transform.position.x, transform.position.y - 0.05f) + new Vector2(boxCollider2D.offset.x, boxCollider2D.offset.y), new Vector2(boxCollider2D.size.x * 0.8f, boxCollider2D.size.y), 0, Vector2.zero, 0, 1 << LayerMask.NameToLayer("Background"));
            animator.SetBool("Fly", !hit);
            #region [보스패턴]
            if (time > 3f / animator.speed)
            {
                animator.speed = (GameManager.GameLevel == TutorialScript.GameLevel.쉬움) ? 1f : (GameManager.Boss_now_hp > GameManager.Boss_max_hp * 0.5f && GameManager.GameLevel == TutorialScript.GameLevel.보통) ? 1f : 1.5f;
                if (pattern == -1)
                {
                    int r = 0;
                    if (boss_time > 6f)
                    {
                        if ((GameManager.Boss_now_hp > GameManager.Boss_max_hp * 0.5f && GameManager.GameLevel == TutorialScript.GameLevel.보통) || GameManager.GameLevel == TutorialScript.GameLevel.쉬움)
                        {
                            do
                            {
                                r = Random.Range(0, 4);
                            } while (backpattern == r);
                        }
                        else
                        {
                            do
                            {
                                r = Random.Range(0, 5);
                            } while (backpattern == r);
                        }
                    }
                    pattern = r;
                }
                if (pattern == 0 || pattern == 1 || pattern == 2)
                {
                    #region [패턴1]
                    if (animator.GetInteger("Pattern") != 1)
                    {
                        animator.SetInteger("Pattern", 1);
                    }
                    if (animator.GetCurrentAnimatorStateInfo(0).IsName("Slime_Pattern0"))
                    {
                        if (animator.GetCurrentAnimatorStateInfo(0).normalizedTime % 1 >= 0.3f && !patterncheck)
                        {
                            fireballcount++;
                            patterncheck = true;
                            Debug.Log("");
                            float levelchange  = (GameManager.GameLevel == TutorialScript.GameLevel.쉬움) ? 1f : (GameManager.Boss_now_hp > GameManager.Boss_max_hp * 0.5f && GameManager.GameLevel == TutorialScript.GameLevel.보통) ? 1f : 2f;
                            float levelchange2 = (GameManager.GameLevel == TutorialScript.GameLevel.쉬움) ? 1f : (GameManager.Boss_now_hp > GameManager.Boss_max_hp * 0.5f && GameManager.GameLevel == TutorialScript.GameLevel.보통) ? 1f : 1.5f;
                            GetComponent <Rigidbody2D>().mass = levelchange * 2;
                            GetComponent <Rigidbody2D>().AddForce(new Vector2(StageManager.player_static.transform.position.x < transform.position.x ? -100 * levelchange : 100 * levelchange, 750 * levelchange2));
                        }
                        else if (!hit && patterncheck)
                        {
                            patterncheck = false;
                        }
                        if (fireballcount > 10 / animator.speed)
                        {
                            backpattern   = pattern;
                            patterncheck  = false;
                            fireballcount = 0;
                            time          = 0;
                            pattern       = -1;
                            animator.SetInteger("Pattern", -1);
                        }
                    }
                    #endregion
                }
                else if (pattern == 3 || pattern == 4)
                {
                    #region [패턴2]
                    if (animator.GetInteger("Pattern") != 2)
                    {
                        animator.SetInteger("Pattern", 2);
                    }
                    if (animator.GetCurrentAnimatorStateInfo(0).IsName("Slime_Pattern1"))
                    {
                        if (animator.GetCurrentAnimatorStateInfo(0).normalizedTime % 1 >= 0.3f && animator.GetCurrentAnimatorStateInfo(0).normalizedTime % 1 <= 0.8f && !patterncheck)
                        {
                            fireballcount++;
                            patterncheck = true;
                            GameObject emp = Instantiate(slime_prefab[Random.Range(0, slime_prefab.Length)], transform.position, Quaternion.identity);
                            emp.GetComponent <Rigidbody2D>().AddForce(new Vector2(0, 100));
                            emp.transform.parent = transform.parent;
                        }
                        else if (animator.GetCurrentAnimatorStateInfo(0).normalizedTime % 1 >= 0.8f && patterncheck)
                        {
                            patterncheck = false;
                        }
                        if (fireballcount > 10 / animator.speed)
                        {
                            backpattern   = pattern;
                            patterncheck  = false;
                            fireballcount = 0;
                            time          = 0;
                            pattern       = -1;
                            animator.SetInteger("Pattern", -1);
                        }
                    }
                    #endregion
                }
            }
            #endregion
        }
        #endregion
    }
    void Update()
    {
        if (able)
        {
            // CHECK IF DEAD
            dead = Physics2D.IsTouchingLayers(player_collider, deathLayer) || Mathf.Abs(player_body.velocity.x) <= 0.01f;
            //grounded = Physics2D.Raycast(player_body.transform.position, Vector2.down, .51f, groundLayer);

            // CHECK IF GROUNDED
            //grounded = checkGrounded && Physics2D.IsTouchingLayers(player_collider, groundLayer);

            if (reversed)
            {
                grounded = Physics2D.BoxCast(player_body.transform.position, new Vector2(mini ? .45f : .95f, .1f), 0f, Vector2.up, .51f, groundLayer) && checkGrounded &&
                           Physics2D.IsTouchingLayers(player_collider, groundLayer);

                regate = -1;
                grounded_particles.gravityModifier      = -Mathf.Abs(grounded_particles.gravityModifier);
                ground_impact_particles.gravityModifier = -Mathf.Abs(ground_impact_particles.gravityModifier);
            }
            else
            {//.9
                grounded = Physics2D.BoxCast(player_body.transform.position, new Vector2(mini ? .45f : .95f, .1f), 0f, Vector2.down, .51f, groundLayer) && checkGrounded &&
                           Physics2D.IsTouchingLayers(player_collider, groundLayer);

                regate = 1;
                grounded_particles.gravityModifier      = Mathf.Abs(grounded_particles.gravityModifier);
                ground_impact_particles.gravityModifier = Mathf.Abs(ground_impact_particles.gravityModifier);
            }

            // IF GROUNDED --> TURN OFF TRAIL

            /*
             * if (grounded && (!red_p && !yellow_p && !blue_p && !pink_p))
             * {
             *  trail.emitting = false;
             *  animator.SetBool("Jump", false);
             *  animator.SetBool("Orb", false);
             * }*/

            // LIMIT Y SPEED
            if (player_body.velocity.y > maxSpeed)
            {
                player_body.velocity = new Vector2(player_body.velocity.x, maxSpeed);
            }
            else if (player_body.velocity.y < -maxSpeed)
            {
                player_body.velocity = new Vector2(player_body.velocity.x, -maxSpeed);
            }


            // Movement Speed
            moveX = speed;

            if (grounded && (Mathf.Abs(player_body.velocity.x) > .1f || jump))
            {
                if (!grounded_particles.isPlaying)
                {
                    grounded_particles.Play();
                }
            }
            else
            {
                if (grounded_particles.isPlaying)
                {
                    grounded_particles.Stop();
                }
            }

            if (!prev_grounded && grounded)
            {
                ground_impact_particles.Play();
            }

            // JUMP!
            if (Input.GetButtonDown("Jump") || Input.GetKeyDown("space") || Input.GetMouseButtonDown(0))
            {
                if (triggerorb)
                {
                    triggerorb_j = true;
                }
                if (teleorb)
                {
                    teleorb_j = true;
                }
                if (yellow)
                {
                    yellow_j = true;
                }
                if (red)
                {
                    red_j = true;
                }
                if (pink)
                {
                    pink_j = true;
                }
                if (blue)
                {
                    blue_j = true;
                }
                if (green)
                {
                    green_j = true;
                }
                if (black)
                {
                    black_j = true;
                }

                jump = true;
            }

            // RELEASE JUMP
            if (Input.GetButtonUp("Jump") || Input.GetKeyUp("space") || Input.GetMouseButtonUp(0))
            {
                jump = false;
            }

            // CHANGE JUMP DIRECTION WHEN REVERSED
            if (reversed)
            {
                jumpForce = -posJump;
                //windUp.gravityModifier = -1;
                //windDown.gravityModifier = -1;
            }
            else
            {
                jumpForce = posJump;
                //windUp.gravityModifier = 1;
                //windDown.gravityModifier = 1;
            }

            // IF DEAD --> RESPAWN
            if (dead)
            {
                dead = false;
                Respawn();
            }
        }
    }
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Application.Quit();
        }
        timeSinceLastJump += Time.deltaTime;
        if (Input.GetAxisRaw("Horizontal") != 0.0f)
        {
            horizontal          = Input.GetAxisRaw("Horizontal");
            transform.position += new Vector3(
                horizontal,
                0.0f,
                0.0f
                ) * speed * Time.deltaTime;
        }

        rb.gravityScale = 1.0f;
        if (IsGrounded())
        {
            if (timeSinceLastJump > jumpDelay)
            {
                jumps = 0;
                if (Input.GetButtonDown("Jump"))
                {
                    rb.AddForce(Vector2.up * jumpHeight, ForceMode2D.Impulse);
                    jumps             = 1;
                    timeSinceLastJump = 0.0f;
                }
            }
        }
        else
        {
            jumps = Mathf.Clamp(jumps, 1, maxJumps);
            if (jumps < maxJumps && Input.GetButtonDown("Jump") && timeSinceLastJump > jumpDelay)
            {
                rb.velocity = new Vector2(rb.velocity.x, 0.0f);
                rb.AddForce(Vector2.up * jumpHeight, ForceMode2D.Impulse);
                jumps++;
                timeSinceLastJump = 0.0f;
            }
            if (rb.velocity.y < 0.0f)
            {
                if (hover && Input.GetButton("Jump"))
                {
                    rb.gravityScale = 0.5f;
                    rb.velocity     = new Vector2(
                        rb.velocity.x,
                        Mathf.Clamp(rb.velocity.y, 0.0f, -1.0f)
                        );
                }
                else
                {
                    rb.gravityScale = 1.7f;
                }
            }
            else if (!Input.GetButton("Jump"))
            {
                rb.gravityScale = 1.4f;
            }
        }

        if (Input.GetButtonDown("Fire1"))
        {
            // Shoot
            GameObject bullet    = Instantiate(bulletPrefab);
            Vector2    direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
            direction.Normalize();
            bullet.transform.position = transform.position +
                                        new Vector3(direction.x, direction.y, 0.0f) * 0.88f +
                                        new Vector3(0.5f, -0.5f, 0.0f);
            bullet.GetComponent <Bullet>().velocity = direction * bulletSpeed;
        }

        if (Input.GetButtonDown("Interact"))
        {
            RaycastHit2D hit = Physics2D.BoxCast(
                new Vector2(col.bounds.min.x, col.bounds.min.y),
                new Vector2(1.0f, 1.0f),
                0.0f,
                new Vector2(Mathf.Sign(horizontal), 0.0f),
                1.0f,
                interactable
                );
            if (hit)
            {
                hit.transform.GetComponent <DialogueHandler>().StartStory();
                if (hit.transform.gameObject.CompareTag("Powerup"))
                {
                    switch (hit.transform.name.ToLower())
                    {
                    case "burst":
                        burst = true;
                        break;

                    case "hover":
                        hover = true;
                        break;

                    case "double jump":
                        maxJumps = 2;
                        break;

                    default:
                        break;
                    }
                    Destroy(hit.transform.gameObject);
                }
            }
        }

        if (burst)
        {
            if (Input.GetMouseButton(1))
            {
                burstCharge += Time.deltaTime;
                if (burstCharge > burstChargeTime)
                {
                    burstCharge = burstChargeTime;
                }
            }

            if (Input.GetMouseButtonUp(1))
            {
                Debug.Log("Burst");
                // Perform burst attack
                GameObject[] objects = GameObject.FindGameObjectsWithTag("Enemy");
                foreach (GameObject go in objects)
                {
                    int damage = Mathf.CeilToInt(burstMaxDamage * burstCharge / burstChargeTime);
                    Debug.Log(damage);
                    go.GetComponent <Enemy>().TakeDamage(damage);
                }
            }
        }
    }
Example #12
0
    void FixedUpdate()
    {
        RaycastHit2D hit = Physics2D.BoxCast(this.transform.position, new Vector2(0.4f, 0.1f), 0f, Vector2.down, groundCheckRadius, groundMask); //using this for a bigger and more accurate ground check

        isTouchingGround = (hit.collider != null) ? true : false;

        movementInput = Input.GetAxis("Horizontal");

        CheckIfStuck(); //Checks if Mario is trying to walk into the wall and get stuck

        if (!isDead)
        {
            if ((playerRigidbody2D.velocity.x > 0 && !isFacingRight) || (playerRigidbody2D.velocity.x < 0 && isFacingRight))
            {
                playerAnimator.SetBool("turning", true);
            }
            else
            {
                playerAnimator.SetBool("turning", false);
            }

            float movementForceMultiplier = Mathf.Max(maxHorizontalSpeed - Mathf.Abs(playerRigidbody2D.velocity.x), 1);

            playerRigidbody2D.AddForce(new Vector2(movementInput * movementForce * movementForceMultiplier, 0));

            playerRigidbody2D.velocity = new Vector2(Mathf.Clamp(playerRigidbody2D.velocity.x, -maxHorizontalSpeed, maxHorizontalSpeed), Mathf.Clamp(playerRigidbody2D.velocity.y, -maxVerticalSpeed, maxVerticalSpeed));

            if (Input.GetKeyDown(KeyCode.Space))
            {
                if (isTouchingGround)
                {
                    //Play Jump sound
                    if (!poweredUp)
                    {
                        audioSource.PlayOneShot(smallJumpSound);
                    }
                    else
                    {
                        audioSource.PlayOneShot(bigJumpSound);
                    }

                    isJumping = true;
                    playerRigidbody2D.velocity = new Vector2(playerRigidbody2D.velocity.x, jumpVelocity);
                    jumpTimeCounter            = jumpTime;
                }
            }

            if (jumpTimeCounter > 0 && isJumping)
            {
                if (Input.GetKey(KeyCode.Space))
                {
                    jumpTimeCounter -= Time.deltaTime;
                    {
                        playerRigidbody2D.velocity = new Vector2(playerRigidbody2D.velocity.x, jumpVelocity);
                    }
                }
            }

            if (Input.GetKeyUp(KeyCode.Space))
            {
                isJumping       = false;
                jumpTimeCounter = 0;
            }

            playerAnimator.SetFloat("movementSpeed", Mathf.Abs(playerRigidbody2D.velocity.x));
            playerAnimator.SetBool("touchingGround", isTouchingGround);
        }

        if (movementInput > 0 && !isFacingRight)
        {
            FlipSprite();
        }
        else if (movementInput < 0 && isFacingRight)
        {
            FlipSprite();
        }
    }
Example #13
0
    private void GroundedCheck()
    {
        RaycastHit2D hit = Physics2D.BoxCast(box.bounds.center, box.bounds.size, 0f, Vector2.down, 0.1f, platforms);

        grounded = hit.collider != null;
    }
Example #14
0
 protected void UpdateCeilinged()
 {
     IsCeilinged = (Physics2D.BoxCast(col.bounds.center, col.bounds.size, 0f, Vector2.up, ceilingCheckDistance, groundLayer.value).collider != null);
 }
Example #15
0
    private IEnumerator RotateArc(Vector3 axis, float angle, float duration)
    {
        float elapsed = 0.0f;
        float rotated = 0.0f;

        duration /= 2;

        while (elapsed < duration)
        {
            float step = angle / duration * Time.deltaTime;
            transform.RotateAround(transform.position, axis, step);
            elapsed += Time.deltaTime;
            rotated += step;


            if (reversed)
            {
                grounded = Physics2D.BoxCast(player_body.transform.position, new Vector2(.9f, .1f), 0f, Vector2.up, .59f, groundLayer) && checkGrounded;
            }
            else
            {
                grounded = Physics2D.BoxCast(player_body.transform.position, new Vector2(.9f, .1f), 0f, Vector2.down, .59f, groundLayer) && checkGrounded;
            }

            if (grounded)
            {
                transform.RotateAround(transform.position, axis, -rotated);
                yield break;
            }

            yield return(null);
            //yield return new WaitForFixedUpdate();
        }
        transform.RotateAround(transform.position, axis, angle - rotated);

        angle  *= -1;
        elapsed = 0.0f;
        rotated = 0.0f;

        while (elapsed < duration)
        {
            float step = angle / duration * Time.deltaTime;
            transform.RotateAround(transform.position, axis, step);
            elapsed += Time.deltaTime;
            rotated += step;

            if (reversed)
            {
                grounded = Physics2D.BoxCast(player_body.transform.position, new Vector2(.9f, .1f), 0f, Vector2.up, 1f, groundLayer) && checkGrounded;
            }
            else
            {
                grounded = Physics2D.BoxCast(player_body.transform.position, new Vector2(.9f, .1f), 0f, Vector2.down, 1f, groundLayer) && checkGrounded;
            }

            if (grounded)
            {
                transform.RotateAround(transform.position, axis, angle - rotated);
                yield break;
            }

            yield return(null);
            //yield return new WaitForFixedUpdate();
        }
        transform.RotateAround(transform.position, axis, angle - rotated);
    }
Example #16
0
    private bool isGrounded()
    {
        RaycastHit2D rayHit = Physics2D.BoxCast(boxCollider.bounds.center, boxCollider.bounds.size, 0.0f, Vector2.down * 0.1f, platLayer);

        return(rayHit);
    }
Example #17
0
    void Update()
    {
        if (able)
        {
            // CHECK IF DEAD
            dead = Physics2D.IsTouchingLayers(player_collider, deathLayer) || Physics2D.IsTouchingLayers(crouch_collider, deathLayer);
            //grounded = Physics2D.Raycast(player_body.transform.position, Vector2.down, .51f, groundLayer);

            // CHECK IF GROUNDED
            if (reversed)
            {
                grounded = Physics2D.BoxCast(player_body.transform.position, new Vector2(mini ? .45f : .95f, .1f), 0f, Vector2.up, .51f, groundLayer) && checkGrounded &&
                           (Physics2D.IsTouchingLayers(player_collider, groundLayer) || Physics2D.IsTouchingLayers(crouch_collider, groundLayer));
                regate = -1;
                grounded_particles.gravityModifier      = -Mathf.Abs(grounded_particles.gravityModifier);
                ground_impact_particles.gravityModifier = -Mathf.Abs(ground_impact_particles.gravityModifier);
            }
            else
            {//.9
                grounded = Physics2D.BoxCast(player_body.transform.position, new Vector2(mini ? .45f : .95f, .1f), 0f, Vector2.down, .51f, groundLayer) && checkGrounded &&
                           (Physics2D.IsTouchingLayers(player_collider, groundLayer) || Physics2D.IsTouchingLayers(crouch_collider, groundLayer));
                regate = 1;
                grounded_particles.gravityModifier      = Mathf.Abs(grounded_particles.gravityModifier);
                ground_impact_particles.gravityModifier = Mathf.Abs(ground_impact_particles.gravityModifier);
            }

            //Debug.Log("Grounded: " + grounded);

            // IF GROUNDED --> TURN OFF TRAIL
            if (grounded)
            {
                trail.emitting = false;
                eyes.transform.Find("Eyes_Normal").gameObject.SetActive(true);
                eyes.transform.Find("Eyes_Wide").gameObject.SetActive(false);
                eyes.transform.Find("Eyes_Squint").gameObject.SetActive(false);
                eyes.transform.Find("Eyes_Irked").gameObject.SetActive(false);

                if (!prev_grounded && prev_velocity > 13)
                {
                    Cube_Anim.ResetTrigger("Crouch");
                    Cube_Anim.ResetTrigger("Default");
                    Cube_Anim.ResetTrigger("Stretch");
                    Cube_Anim.SetTrigger("Squash");
                }
            }

            // LIMIT Y SPEED
            if (player_body.velocity.y > maxSpeed)
            {
                player_body.velocity = new Vector2(player_body.velocity.x, maxSpeed);
            }
            else if (player_body.velocity.y < -maxSpeed)
            {
                player_body.velocity = new Vector2(player_body.velocity.x, -maxSpeed);
            }


            // Movement Speed
            moveX = Input.GetAxisRaw("Horizontal") * speed;

            // Grounded Particles
            if (grounded && (Mathf.Abs(player_body.velocity.x) > .1f || jump))
            {
                if (!grounded_particles.isPlaying)
                {
                    grounded_particles.Play();
                }
            }
            else
            {
                grounded_particles.Stop();
            }

            if ((prev_grounded && !grounded) || (!prev_grounded && grounded && prev_velocity > 10f))
            {
                ground_impact_particles.Play();
            }

            // JUMP!
            if (Input.GetButtonDown("Jump") || Input.GetKeyDown("space") || Input.GetMouseButtonDown(0))
            {
                jump       = true;
                released   = false;
                fromGround = ((grounded || time < .07f) && jump);

                if (!reversed && player_body.velocity.y <= 1)
                {
                    downjump = true;
                }
                else if (reversed && player_body.velocity.y >= -1)
                {
                    downjump = true;
                }
                else
                {
                    downjump = false;
                }
            }

            // RELEASE JUMP
            if (Input.GetButtonUp("Jump") || Input.GetKeyUp("space") || Input.GetMouseButtonUp(0))
            {
                jump     = false;
                released = true;
            }

            float hitDist = mini ? 0 : .6f;
            if (!reversed)
            {
                headHit = Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y - .2f), Vector2.up, hitDist, groundLayer);
            }
            else
            {
                headHit = Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y + .2f), -Vector2.up, hitDist, groundLayer);
            }
            int rev = reversed ? -1 : 1;
            Debug.DrawLine(transform.position - new Vector3(-1, rev * .2f, 0), transform.position + new Vector3(1, rev * hitDist, 0), Color.red);
            //Debug.Log("headHit: " + headHit.distance);

            // CROUCH
            if (Input.GetAxisRaw("Vertical") < 0 || Input.GetKey(KeyCode.LeftShift) || Input.GetMouseButton(1) || headHit.distance > 0)
            {
                crouch = true;
            }
            else
            {
                crouch = false;
            }

            // CHANGE JUMP DIRECTION WHEN REVERSED
            if (reversed)
            {
                jumpForce = -posJump;
            }
            else
            {
                jumpForce = posJump;
            }

            // IF DEAD --> RESPAWN
            if (dead)
            {
                dead = false;
                Respawn();
            }

            prev_grounded = grounded;
            prev_velocity = Mathf.Abs(player_body.velocity.y);

            time += Time.deltaTime;
            if (prev_grounded)
            {
                time = 0;
            }
        }
    }
        /// <summary>
        /// Returns true if a target is found by the ray
        /// </summary>
        /// <returns></returns>
        protected virtual bool DetectTarget()
        {
            if (_orientation2D == null)
            {
                return(false);
            }

            bool hit = false;

            _distanceToTarget = 0;
            Transform    target = null;
            RaycastHit2D raycast;

            _drawLeftGizmo  = false;
            _drawRightGizmo = false;

            _boxcastSize.x = DetectionDistance / 5f;
            _boxcastSize.y = RayWidth;

            _facingDirection = _orientation2D.IsFacingRight ? Vector2.right : Vector2.left;
            // we cast a ray to the left of the agent to check for a Player
            _raycastOrigin.x = transform.position.x + _facingDirection.x * DetectionOriginOffset.x / 2;
            _raycastOrigin.y = transform.position.y + DetectionOriginOffset.y;

            // we cast it to the left
            if ((DetectionDirection == DetectionDirections.Both) ||
                ((DetectionDirection == DetectionDirections.Front) && (!_orientation2D.IsFacingRight)) ||
                ((DetectionDirection == DetectionDirections.Back) && (_orientation2D.IsFacingRight)))
            {
                if (DetectMethod == DetectMethods.Ray)
                {
                    raycast = MMDebug.RayCast(_raycastOrigin, Vector2.left, DetectionDistance, TargetLayer, MMColors.Gold, true);
                }
                else
                {
                    raycast = Physics2D.BoxCast(_raycastOrigin + Vector2.right * _boxcastSize.x / 2f, _boxcastSize, 0f, Vector2.left, DetectionDistance, TargetLayer);
                    MMDebug.RayCast(_raycastOrigin + Vector2.up * RayWidth / 2f, Vector2.left, DetectionDistance, TargetLayer, MMColors.Gold, true);
                    MMDebug.RayCast(_raycastOrigin - Vector2.up * RayWidth / 2f, Vector2.left, DetectionDistance, TargetLayer, MMColors.Gold, true);
                    MMDebug.RayCast(_raycastOrigin - Vector2.up * RayWidth / 2f + Vector2.left * DetectionDistance, Vector2.up, RayWidth, TargetLayer, MMColors.Gold, true);
                    _drawLeftGizmo = true;
                }

                // if we see a player
                if (raycast)
                {
                    hit               = true;
                    _direction        = Vector2.left;
                    _distanceToTarget = Vector2.Distance(_raycastOrigin, raycast.point);
                    target            = raycast.collider.gameObject.transform;
                }
            }

            // we cast a ray to the right of the agent to check for a Player
            if ((DetectionDirection == DetectionDirections.Both) ||
                ((DetectionDirection == DetectionDirections.Front) && (_orientation2D.IsFacingRight)) ||
                ((DetectionDirection == DetectionDirections.Back) && (!_orientation2D.IsFacingRight)))
            {
                if (DetectMethod == DetectMethods.Ray)
                {
                    raycast = MMDebug.RayCast(_raycastOrigin, Vector2.right, DetectionDistance, TargetLayer, MMColors.DarkOrange, true);
                }
                else
                {
                    raycast = Physics2D.BoxCast(_raycastOrigin - Vector2.right * _boxcastSize.x / 2f, _boxcastSize, 0f, Vector2.right, DetectionDistance, TargetLayer);
                    MMDebug.RayCast(_raycastOrigin + Vector2.up * RayWidth / 2f, Vector2.right, DetectionDistance, TargetLayer, MMColors.DarkOrange, true);
                    MMDebug.RayCast(_raycastOrigin - Vector2.up * RayWidth / 2f, Vector2.right, DetectionDistance, TargetLayer, MMColors.DarkOrange, true);
                    MMDebug.RayCast(_raycastOrigin - Vector2.up * RayWidth / 2f + Vector2.right * DetectionDistance, Vector2.up, RayWidth, TargetLayer, MMColors.DarkOrange, true);
                    _drawLeftGizmo = true;
                }

                if (raycast)
                {
                    hit               = true;
                    _direction        = Vector2.right;
                    _distanceToTarget = Vector2.Distance(_raycastOrigin, raycast.point);
                    target            = raycast.collider.gameObject.transform;
                }
            }

            if (hit)
            {
                // we make sure there isn't an obstacle in between
                float        distance        = Vector2.Distance((Vector2)target.transform.position, _raycastOrigin);
                RaycastHit2D raycastObstacle = MMDebug.RayCast(_raycastOrigin, ((Vector2)target.transform.position - _raycastOrigin).normalized, distance, ObstaclesLayer, Color.gray, true);

                if (raycastObstacle && _distanceToTarget > raycastObstacle.distance)
                {
                    _brain.Target = null;
                    return(false);
                }
                else
                {
                    // if there's no obstacle, we store our target and return true
                    _brain.Target = target;
                    return(true);
                }
            }
            _brain.Target = null;
            return(false);
        }
Example #19
0
    // detects collision objects around the player and prevents movement into them
    // redefined by me to provide smoother functionality and greater control over the default rigidbody collision mechanics
    void DetectCollision()
    {
        Vector2 v;
        Vector2 pScaleX;         // player scale
        Vector2 pScaleY;         // player scale
        float   xDist = velocity.x * Time.deltaTime;

        // offset detection origin. If offset is too small, player can occasionally clip through walls.
        // player is 0.025 units inside a wall at closest., need to offset boxcast by at least that much for it to always work
        v = new Vector2(transform.position.x - collision.OFFSET, transform.position.y - 0f);

        pScaleX = new Vector2(0.01f, boxCollider.size.y * transform.localScale.y * collision.LR_COLLISION_HEIGHT_MULT);          // localscale may not be needed
        pScaleY = new Vector2(boxCollider.size.x * transform.localScale.x * collision.UD_COLLISION_HEIGHT_MULT, 0.01f);

        //pScaleX = new Vector2(1f, 5f);

        // smaller check if crouching
        float local_ray_distance_up   = collision.RAY_DISTANCE_UP;
        float local_ray_distance_down = collision.RAY_DISTANCE_DOWN;

        // check right collision (only if moving right)
        rayHit = Physics2D.BoxCast(v, pScaleX, 0f, Vector2.right, Mathf.Max(collision.RAY_DISTANCE_LR, xDist), collisionMask);
        Debug.DrawRay(v, Vector2.right * Mathf.Max(collision.RAY_DISTANCE_LR, xDist), Color.yellow);
        if (rayHit && velocity.x > 0)
        {
            rightCollision = true;
            velocity.x     = 0;                                                                     // stop player movement
            this.transform.Translate(Vector3.left * (collision.RAY_DISTANCE_LR - rayHit.distance)); // set their position to be at the edge of the object they collided with
            //print("collision RIGHT: " + (collision.RAY_DISTANCE_LR - rayHit.distance) + " = " + collision.RAY_DISTANCE_LR + " + " + rayHit.distance);
        }

        // if currently colliding, check for the absense of collision
        if (rightCollision)
        {
            rayHit = Physics2D.BoxCast(v, pScaleX, 0f, Vector2.right, collision.RAY_DISTANCE_LR, collisionMask);
            if (!rayHit)
            {
                rightCollision = false;
            }
        }

        // change offset for new direction
        v += new Vector2(2 * collision.OFFSET, 0);

        // check left collision (only if moving left), same logic as right collision
        // raycast distance = set distance, OR distance the player will travel in this frame, whichever is higher.
        rayHit = Physics2D.BoxCast(v, pScaleX, 0f, Vector2.left, Mathf.Max(collision.RAY_DISTANCE_LR, -xDist), collisionMask);
        Debug.DrawRay(v, Vector2.left * Mathf.Max(collision.RAY_DISTANCE_LR, xDist), Color.yellow);
        if (rayHit && velocity.x < 0)
        {
            leftCollision = true;

            velocity.x = 0;
            this.transform.Translate(Vector2.right * (collision.RAY_DISTANCE_LR - rayHit.distance));
        }

        if (leftCollision)
        {
            rayHit = Physics2D.BoxCast(v, pScaleX, 0f, Vector2.left, collision.RAY_DISTANCE_LR, collisionMask);
            if (!rayHit)
            {
                leftCollision = false;
            }
        }

        // check up collision
        float upStrictness = collision.UP_COLLISION_STRICTNESS_FACTOR + 1f;

        rayHit = Physics2D.BoxCast(transform.position, pScaleY, 0f, Vector2.up, local_ray_distance_up, collisionMask);
        Debug.DrawRay(v, Vector2.up * Mathf.Max(local_ray_distance_up, xDist), Color.yellow);
        if (rayHit && (velocity.y > 0 || onGround))         // used to be just velocity.y > 0, changed for crouching to work
        {
            upCollision = true;
            velocity.y  = 0;
            this.transform.Translate(Vector2.down * (local_ray_distance_up - rayHit.distance));
            //print("collision UP: " + (collision.RAY_DISTANCE_UP - rayHit.distance) + " = " + collision.RAY_DISTANCE_UP + " + " + rayHit.distance);
        }
        else
        {
            upCollision = false;
        }

        // check down collision
        rayHit = Physics2D.BoxCast(transform.position, pScaleY, 0f, Vector2.down, local_ray_distance_down, collisionMask);
        Debug.DrawRay(v, Vector2.down * Mathf.Max(local_ray_distance_down, xDist), Color.yellow);
        if (rayHit /* && velocity.y < 0 */) // y < 0 may sometimes eat jump input.
        {
            onGround = true;                // player considered on the ground if colliding with something downwards
            //onGroundGraceTimerState = 0;
            if (!isJumping)                 // this clause allows the player to leave the ground again
            {
                velocity.y = 0;
                this.transform.Translate(Vector2.up * (local_ray_distance_down - rayHit.distance));
                //print("collision DOWN: " + (collision.RAY_DISTANCE_DOWN - rayHit.distance) + " = " + collision.RAY_DISTANCE_DOWN + " + " + rayHit.distance);
            }
        }
        else                                                                                                                          // player not on the ground
        {
            rayHit = Physics2D.BoxCast(transform.position, pScaleY, 0f, Vector2.down, local_ray_distance_down + 0.3f, collisionMask); // slightly longer raycast
            if (rayHit && !isJumping && onGround)                                                                                     // if ground is only slightly beneath player, and they didnt jump, were on the ground last frame, and werent knocked back, its a slope
            {
                //print("SLOPE " + rayHit.distance);
                this.transform.Translate(Vector2.down * (rayHit.distance - local_ray_distance_down));
            }
            else
            {
                onGround = false;
            }
        }

        // Grace timer
        // gives player a short amount of time before conisdering them off the ground.
        switch (onGroundGraceTimerState)
        {
        case 0:                 // primed
            if (!onGround)      // activate when player leaves the ground
            {
                if (!isJumping)
                {
                    onGroundGraceTimerState = 1;                             // 1: active
                    onGroundGraceTimer      = 0f;
                }
                else
                {
                    onGroundGraceTimerState = 2;                             // expend grace timer if player left the ground via jumping or dashing.
                }
            }

            break;

        case 1:                         // active
            onGround            = true; //override collision
            onGroundGraceTimer += Time.deltaTime;

            if (onGroundGraceTimer >= general.ON_GROUND_GRACE_MAX || isJumping)
            {
                onGround = false;
                onGroundGraceTimerState = 2;                         // 2: expended
            }
            break;

        case 2:                 // expended
            if (onGround)
            {
                onGroundGraceTimerState = 0;                            // NEVER CALLED RIGHT NOW, FIX
            }
            break;
        }
    }
Example #20
0
    private void CheckIsGround()
    {
        RaycastHit2D hit2d = Physics2D.BoxCast(this.transform.position, this.boxSize, 0f, Vector2.down, distance, this.layerMask);

        this.isGround = hit2d.collider != null;
    }
Example #21
0
    private bool isGrounded()
    {
        RaycastHit2D raycast = Physics2D.BoxCast(boxCollider.bounds.center, boxCollider.bounds.size, 0f, Vector2.down * 0.1f, layerMask);

        return(raycast.collider != null);
    }
Example #22
0
    // Update is called once per frame
    void Update()
    {
        //Debug.DrawRay(transform.position, Vector2.down *2, Color.yellow);

        transform.position = new Vector3(
            transform.position.x,
            transform.position.y,
            0.0f);

        //bool hit = Physics2D.Linecast(
        //        transform.position,
        //        groundTarget.position,
        //        1 << LayerMask.NameToLayer("Ground"));


        isGrounded = Physics2D.BoxCast(
            transform.position,
            new Vector2(2.0f, 1.0f), 0.0f,
            Vector2.down, 1.0f,
            1 << LayerMask.NameToLayer("Ground"));


        // Idle
        if (Input.GetAxis("Horizontal") == 0)
        {
            animator.SetInteger("AnimState", (int)HeroAnimState.IDLE);
            heroAnimState = HeroAnimState.IDLE;
        }


        // moving to the right
        if ((Input.GetAxis("Horizontal") > 0) && (isGrounded))
        {
            animator.SetInteger("AnimState", (int)HeroAnimState.WALK);
            heroAnimState        = HeroAnimState.WALK;
            spriteRenderer.flipX = false;
            playerRigidBody.AddForce(Vector2.right * 30.0f);
        }

        // moving to the left
        if ((Input.GetAxis("Horizontal") < 0) && (isGrounded))
        {
            animator.SetInteger("AnimState", (int)HeroAnimState.WALK);
            heroAnimState        = HeroAnimState.WALK;
            spriteRenderer.flipX = true;
            playerRigidBody.AddForce(Vector2.left * 30.0f);
        }

        // jumping
        if ((Input.GetAxis("Jump") > 0) && (isGrounded))
        {
            animator.SetInteger("AnimState", (int)HeroAnimState.JUMP);
            heroAnimState = HeroAnimState.JUMP;
            jumpSound.Play();
            playerRigidBody.AddForce(Vector2.up * jumpForce);

            isGrounded = false;
        }

        // not jumping
        if (Input.GetKeyUp(KeyCode.Space))
        {
            animator.SetInteger("AnimState", (int)HeroAnimState.IDLE);
            heroAnimState = HeroAnimState.IDLE;
        }

        playerRigidBody.velocity =
            new Vector2(
                Mathf.Clamp(playerRigidBody.velocity.x,
                            -maximumVelocity.x, maximumVelocity.x),
                Mathf.Clamp(playerRigidBody.velocity.y,
                            -maximumVelocity.y, maximumVelocity.y));
    }
Example #23
0
    // Update is called once per frame
    void Update()
    {
        //inputs
        if (player != null)
        {
            horizontalInput    = player.GetAxis("Horizontal");
            verticalInput      = player.GetAxis("Vertical");
            aimHorizontalInput = player.GetAxis("AimHorizontal");
            aimVerticalInput   = player.GetAxis("AimVertical");
            if (aimHorizontalInput != 0 && aimVerticalInput != 0)
            {
                aimDirection = new Vector2(aimHorizontalInput, aimVerticalInput).normalized;
            }
            throwInput    = player.GetButton("Throw");
            interactInput = player.GetButton("Interact");
            jumpInput     = player.GetButton("Jump");
            if (player.GetButtonDown("Jump") && isGrounded)
            {
                //apply an impulse when the player presses jump
                rb.AddForce(Vector2.up * jumpImpulse, ForceMode2D.Impulse);
                jumpHold   = true;
                isGrounded = false;
                currentJumpHoldVelocity = jumpHoldVelocity;
                audioSource.PlayOneShot(audioJump);
                //jump particles
                if (jumpParticlesPrefab != null)
                {
                    Instantiate(jumpParticlesPrefab, transform.position, Quaternion.identity);
                }
            }
            if (!jumpInput)
            {
                jumpHold = false;
            }

            //swap resources
            if (player.GetButtonDown("SwapRight"))
            {
                resourceThrower.SwapResourceRight();
            }
            if (player.GetButtonDown("SwapLeft"))
            {
                resourceThrower.SwapResourceLeft();
            }
        }

        //deceleration
        if (horizontalInput >= 0 && currentSpeed < 0)
        {
            currentSpeed += deceleration * Time.deltaTime;
            if (currentSpeed > 0)
            {
                currentSpeed = 0;
            }
        }
        if (horizontalInput <= 0 && currentSpeed > 0)
        {
            currentSpeed -= deceleration * Time.deltaTime;
            if (currentSpeed < 0)
            {
                currentSpeed = 0;
            }
        }

        //acceleration
        if (horizontalInput > 0)
        {
            if (currentSpeed < 1)
            {
                currentSpeed += acceleration * Time.deltaTime;
                if (currentSpeed >= 1)
                {
                    currentSpeed = 1;
                }
            }
        }
        if (horizontalInput < 0)
        {
            if (currentSpeed > -1)
            {
                currentSpeed -= acceleration * Time.deltaTime;
                if (currentSpeed <= -1)
                {
                    currentSpeed = -1;
                }
            }
        }

        //the force gained by holding jump decreases over time
        currentJumpHoldVelocity = Mathf.Max(0, currentJumpHoldVelocity - jumpHoldVelocityDecay * Time.deltaTime);

        //are we grounded?
        RaycastHit2D boxCast = Physics2D.BoxCast(transform.position, new Vector2(boxCollider.size.x, boxCollider.size.y / 2), 0, Vector2.down, boxCollider.size.y / 2 + 0.1f, groundLayers);

        if (boxCast.collider != null)
        {
            if (!isGrounded)
            {
                if (landParticlesPrefab != null)
                {
                    Instantiate(landParticlesPrefab, transform.position, Quaternion.identity);
                }
            }
            isGrounded = true;
        }
        else
        {
            isGrounded = false;
        }


        // Interact with breakable objects
        if (interactInput)
        {
            Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, interactRadius, 1 << LayerMask.NameToLayer("Breakable"));
            foreach (Collider2D breakableCollider in colliders)
            {
                Breakable breakable = breakableCollider.GetComponentInParent <Breakable>();
                if (breakable != null)
                {
                    breakable.Activate();
                }
            }
        }
    }
Example #24
0
    private bool isGround()
    {
        RaycastHit2D rayC2D = Physics2D.BoxCast(boxC2D.bounds.center, boxC2D.bounds.size, 0f, Vector2.down, .1f, PlatformLM);

        return(rayC2D.collider != null);
    }
Example #25
0
    //Check is player is on a surface
    private bool isGrounded()
    {
        RaycastHit2D raycastHit2D = Physics2D.BoxCast(boxCollider2d.bounds.center, boxCollider2d.bounds.size, 0f, Vector2.down, 0.01f, floorLayerMask);

        return(raycastHit2D.collider != null);
    }
Example #26
0
    void Update()
    {
        Vector2 curPos    = this.transform.position;
        float   speedRate = 0;

        //if (Input.GetKey(KeyCode.LeftShift) && rb.velocity.y == 0)
        //{
        //    speedRate = runSpeed;
        //}
        if ((Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D)))
        {
            speedRate = walkSpeed;
        }

        if (speedRate != 0 && !source.isPlaying && isGrounded)
        {
            source.PlayOneShot(walk);
        }

        animator.SetFloat("Speed", speedRate);


        // Just a shortcut to get back to the main menu
        if (Input.GetKey(KeyCode.F1))
        {
            SceneManager.LoadScene("Main Menu");
        }



        // Attacking Mechanic
        if (Input.GetKeyDown(KeyCode.Space) && attackCoolDown <= 0)
        {
            //attackCoolDown = orgCoolDown;
            attackBox.SetActive(true);
            animator.SetBool("attacking", true);
            source.PlayOneShot(attack);
            attackCoolDown = orgCoolDown;
        }
        else
        {
            attackBox.SetActive(false);
            animator.SetBool("attacking", false);
        }


        if (attackCoolDown > 0)
        {
            attackCoolDown -= Time.deltaTime;
        }



        // For flash effect for player when damaged
        if (wasDamaged && flashEffectTimer > 0)
        {
            //Debug.Log("Flash Effect playing?");

            flashEffectCoolDown -= Time.deltaTime;
            if (flashEffectCoolDown <= 0)
            {
                // Debug.Log("Off");
                gameObject.GetComponent <SpriteRenderer>().enabled = false;
                flashEffectCoolDown = 0.05f;
            }
            else
            {
                //Debug.Log("On");
                gameObject.GetComponent <SpriteRenderer>().enabled = true;
                attackCoolDown -= Time.deltaTime;
            }

            flashEffectTimer -= Time.deltaTime;
            if (flashEffectTimer <= 0)
            {
                wasDamaged = false;
                gameObject.GetComponent <SpriteRenderer>().enabled = true;
                flashEffectTimer = orgFlashEffectTimer;
            }
        }



        if (isGrounded)
        {
            animator.SetBool("fallingDown", false);
            if (isFalling)
            {
                source.PlayOneShot(land);
                isFalling = false;
                check2    = -5;
                check     = 0;
            }
        }

        //print(isFalling);
        // While they aren't on the ground, keep checking to see if they
        // are beginning to fall or not
        if (!isGrounded)
        {
            check = transform.position.y;

            if (check2 < check)
            {
                check2    = check;
                isFalling = false;
            }
            else
            {
                isFalling = true;
            }
        }

        // Play falling down animation at the last moment
        if (isFalling)
        {
            RaycastHit2D hit = Physics2D.BoxCast(groundCheck.position, new Vector2(3, 5), 0, -Vector2.up, 5, whatIsGround);
            if (hit.distance < temp)
            {
                //print("hit.distance is less then temp");
                print(hit.distance + " Distance success");
                print(temp + " temp success");
                animator.SetBool("jumping", false);
                animator.SetBool("fallingDown", true);
                isFalling = false;
            }
        }
        //else if (isGrounded && isFalling)
        //{
        //    animator.SetBool("jumping", false);
        //    animator.SetBool("fallingDown", true);
        //}
    }
Example #27
0
    // Update is called once per frame
    void Update()
    {
        // LINE~~~~~~!~!~!~!~!~
        if (drawLine)
        {
            line.positionCount = 2; // 선 보이기

            Vector3 mp = Input.mousePosition;
            mp.z = 10;
            Vector3 delta = Camera.main.ScreenToWorldPoint(mp) - transform.position;

            Vector3 dir      = delta.normalized; // 화살표 방향
            float   distance = 5f;               // 화살표 길이
            line.SetPosition(0, transform.position);
            line.SetPosition(1, transform.position + dir * distance);
        }
        else
        {
            line.positionCount = 0; // 선 없애기
        }
        // ground check
        RaycastHit2D hit = Physics2D.BoxCast(bb.bounds.center, bb.bounds.extents * 2, 0, new Vector2(0, -1), groundCheckDist, 1 << LayerMask.NameToLayer("Ground"));

        if (hit.transform != null)
        {
            onGround = true;
        }
        else
        {
            onGround = false;
        }
        // Debug.DrawLine(bb.bounds.center, bb.bounds.center + bb.bounds.extents + new Vector3(0, -1) * groundCheckDist);


        // 스킬!!!
        if (Input.GetKey(KeyCode.Q)) // 불 알
        {
            skillIdx = SKILL.fire;
        }
        else
        {
            skillIdx = SKILL.pyung;
        }

        // 포션!!!
        if (Input.GetKeyDown(KeyCode.G))
        {
            if (manaPotionLeft > 0)
            {
                manaPotionLeft--;
                mana = 100;

                ShowText("포션 들이킴! (" + manaPotionLeft + "개 남음)"); // WTF LOL

                particleMana.Play();
            }
            else
            {
                ShowText("포션이 바닥났습니다;");
            }
        }

        if (skillIdx != SKILL.none)
        {
            if (skillIdx != SKILL.pyung)
            {
                drawLine = true;
            }
            else
            {
                drawLine = false;
            }

            if (Input.GetMouseButtonDown(0))
            {
                FireMagic();
            }
        }
        else
        {
            drawLine = false;
        }

        // input
        int  moveH    = (Input.GetKey(KeyCode.D) ? 1 : 0) - (Input.GetKey(KeyCode.A) ? 1 : 0);
        bool moveJump = Input.GetKey(KeyCode.Space);

        if (!isKnockBack)
        {
            if (moveH != 0)
            {
                if (rb.velocity.x * moveH < moveVel)
                {
                    rb.velocity += new Vector2(moveH, 0);
                }
                else
                {
                    rb.velocity = new Vector2(moveH * moveVel, rb.velocity.y);
                }
            }
            else
            {
                rb.velocity *= new Vector2(friction, 1);
            }

            if (moveJump && onGround)
            {
                onGround    = false;
                rb.velocity = new Vector2(rb.velocity.x, 10);
            }
        }
    }
Example #28
0
    void Update()
    {
        RaycastHit2D hit = Physics2D.BoxCast(transform.position + groundCollPosition, groundCollSize, 0f, Vector2.zero, 0f, collideWithFloorLayer);

        if (hit == true)
        {
            if (hit.transform.gameObject.layer == LayerMask.NameToLayer("JumpThroughPlatforms"))
            {
                if (rb.velocity.y < 0 && (transform.position.y + groundCollPosition.y - (groundCollSize.y / 2)) >= (hit.transform.position.y - hit.transform.GetComponent <BoxCollider2D>().size.y / 4))
                {
                    isGrounded = true;
                    hit2       = hit;

                    Physics2D.IgnoreCollision(GetComponent <Collider2D>(), hit.transform.GetComponent <Collider2D>(), false);
                    hitPlatform = true;
                }
            }
            else
            {
                isGrounded  = true;
                hitPlatform = false;
            }
        }
        else
        {
            isGrounded = false;
            if (hit2 == true)
            {
                Physics2D.IgnoreCollision(GetComponent <Collider2D>(), hit2.transform.GetComponent <Collider2D>(), true);
                hitPlatform = false;
                hit2        = hit;
            }
        }

        if (isGrounded == true)
        {
            if (hit.collider != null && Mathf.Abs(hit.normal.x) > 0.1f)
            {
                Rigidbody2D body = GetComponent <Rigidbody2D>();
                //body.velocity = new Vector2(body.velocity.x - (hit.normal.x * slopeFriction), body.velocity.y);

                Vector2 position = transform.position;
                //position.y += -hit.normal.x * Mathf.Abs(body.velocity.x) * Time.deltaTime * (body.velocity.x - hit.normal.x > 0 ? 1 : -1);
                transform.position = position;
            }
        }

        if (movement != null)
        {
            var   wallHits     = new RaycastHit2D[10];
            float positionX    = transform.position.x + (wallCollPosition.x * transform.localScale.x);
            float positionY    = transform.position.y;
            int   wallHitCount = (Physics2D.BoxCast(new Vector2(positionX, positionY), wallCollSize, 0f, Vector2.zero, new ContactFilter2D {
                useLayerMask = true, layerMask = collideWithWallLayer
            }, wallHits));
            isWalled = wallHitCount > 0;

            if (isWalled == true)
            {
                movement.StopMovement();
            }
            else
            {
                movement.ContinueMovement();
            }
        }
    }
 bool GroundDetect()
 {
     return(Physics2D.BoxCast(transform.position - new Vector3(0, boxSize.y / 2), boxSize, 0, Vector2.right, 0, groundLayers));
 }
    bool IsCollided(Vector2 direction)
    {
        RaycastHit2D raycast = Physics2D.BoxCast(col.bounds.center, col.bounds.size, 0f, direction, 0.01f, platformLayer);

        return(raycast.collider != null);
    }