コード例 #1
0
    void Rotation()
    {
        float angle = Input.GetAxis("Horizontal");

        rigid.AddTorque(angleForce * -angle, ForceMode2D.Force);
    }
コード例 #2
0
 // Start is called before the first frame update
 void Start()
 {
     meteorr2d = GetComponent <Rigidbody2D>();
     meteorr2d.AddTorque(Random.Range(-30f, 30f));
 }
コード例 #3
0
 private void ThrustRotation()
 {
     rb.AddTorque(_hInput * turnThrustPower * Time.deltaTime);
 }
コード例 #4
0
 // Use this for initialization
 void Start()
 {
     sporeRB = GetComponent <Rigidbody2D>();
     sporeRB.AddForce(new Vector2(Random.Range(-sporeAngle, sporeAngle), Random.Range(sporeSpeedLow, sporeSpeedHigh)), ForceMode2D.Impulse); //Add explosive force in Random X/Y direction.
     sporeRB.AddTorque(Random.Range(-sporeTorqueAngle, sporeTorqueAngle));
 }
コード例 #5
0
ファイル: Natural.cs プロジェクト: takosura/MPC_forDrone
    // Update is called once per frame
    void Update()
    {
        switch (CONTROL_MODE)
        {
        case 0:
            PowerIndicaterTransformLeft.localScale     = new Vector3(0.05f, mpc_1.LeftPower[0] / 3, 1);
            PowerIndicaterTransformLeft.localPosition  = new Vector3(-0.45f, mpc_1.LeftPower[0] / 3 / 2 + 0.5f, 0);
            PowerIndicaterTransformRight.localScale    = new Vector3(0.05f, mpc_1.RightPower[0] / 3, 1);
            PowerIndicaterTransformRight.localPosition = new Vector3(0.45f, mpc_1.RightPower[0] / 3 / 2 + 0.5f, 0);
            lineRenderer.SetPosition(0, new Vector3(mpc_1.BodyPosition_x[0], mpc_1.BodyPosition_y[0], -0.9f));
            for (int i = 1; i < PredictionTime; i++)
            {
                PredictivePositionIndicaterTransform[i].position = new Vector3(mpc_1.BodyPosition_x[i], mpc_1.BodyPosition_y[i], -1f);
                PositionIndicaterPosition[i] = new Vector3(PredictivePositionIndicaterTransform[i].position.x, PredictivePositionIndicaterTransform[i].position.y, -0.9f);
                lineRenderer.SetPosition(i, PositionIndicaterPosition[i]);
            }
            float CurrentBodyAngle1 = BodyTransform.localEulerAngles.z < 180? BodyTransform.localEulerAngles.z: BodyTransform.localEulerAngles.z - 360;
            rb.AddForce(new Vector2((LeftPower + RightPower) * Mathf.Sin(-CurrentBodyAngle1 * DegToRad), (LeftPower + RightPower) * Mathf.Cos(CurrentBodyAngle1 * DegToRad)));
            rb.AddTorque(TorqueConstant * (RightPower - LeftPower));
            break;

        case 1:
            PowerIndicaterTransformLeft.localScale     = new Vector3(mpc_2.Force_x[0] / 1, 0.5f, 1);
            PowerIndicaterTransformLeft.localPosition  = new Vector3(mpc_2.Force_x[0] / 1 / 2, 0, 0);
            PowerIndicaterTransformRight.localScale    = new Vector3(0.05f, mpc_2.Force_y[0] / 1, 1);
            PowerIndicaterTransformRight.localPosition = new Vector3(0, mpc_2.Force_y[0] / 1 / 2, 0);
            lineRenderer.SetPosition(0, new Vector3(mpc_2.BodyPosition_x[0], mpc_2.BodyPosition_y[0], -0.9f));
            for (int i = 1; i < PredictionTime; i++)
            {
                PredictivePositionIndicaterTransform[i].position = new Vector3(mpc_2.BodyPosition_x[i], mpc_2.BodyPosition_y[i], -1f);
                PositionIndicaterPosition[i] = new Vector3(PredictivePositionIndicaterTransform[i].position.x, PredictivePositionIndicaterTransform[i].position.y, -0.9f);
                lineRenderer.SetPosition(i, PositionIndicaterPosition[i]);
            }
            rb.AddForce(new Vector2(Force_x, Force_y));
            break;

        case 2:
            LeftPower  = mpc_3.LeftPower[0];
            RightPower = mpc_3.RightPower[0];
            PowerIndicaterTransformLeft.localScale     = new Vector3(0.05f, LeftPower / 3, 1);
            PowerIndicaterTransformLeft.localPosition  = new Vector3(-0.45f, LeftPower / 3 / 2 + 0.5f, 0);
            PowerIndicaterTransformRight.localScale    = new Vector3(0.05f, RightPower / 3, 1);
            PowerIndicaterTransformRight.localPosition = new Vector3(0.45f, RightPower / 3 / 2 + 0.5f, 0);
            lineRenderer.SetPosition(0, new Vector3(mpc_3.BodyPosition_x[0], mpc_3.BodyPosition_y[0], -0.9f));
            for (int i = 1; i < PredictionTime; i++)
            {
                PredictivePositionIndicaterTransform[i].position = new Vector3(mpc_3.BodyPosition_x[i], mpc_3.BodyPosition_y[i], -1f);
                PositionIndicaterPosition[i] = new Vector3(PredictivePositionIndicaterTransform[i].position.x, PredictivePositionIndicaterTransform[i].position.y, -0.9f);
                lineRenderer.SetPosition(i, PositionIndicaterPosition[i]);
            }
            float CurrentBodyAngle2 = BodyTransform.localEulerAngles.z < 180? BodyTransform.localEulerAngles.z: BodyTransform.localEulerAngles.z - 360;
            rb.AddForce(new Vector2((LeftPower + RightPower) * Mathf.Sin(-CurrentBodyAngle2 * DegToRad), (LeftPower + RightPower) * Mathf.Cos(CurrentBodyAngle2 * DegToRad)));
            rb.AddTorque(TorqueConstant * (RightPower - LeftPower));
            break;

        case 3:
            PowerIndicaterTransformLeft.localScale     = new Vector3(0.05f, mpc_4.LeftForce / 3, 1);
            PowerIndicaterTransformLeft.localPosition  = new Vector3(-0.45f, mpc_4.LeftForce / 3 / 2 + 0.5f, 0);
            PowerIndicaterTransformRight.localScale    = new Vector3(0.05f, mpc_4.RightForce / 3, 1);
            PowerIndicaterTransformRight.localPosition = new Vector3(0.45f, mpc_4.RightForce / 3 / 2 + 0.5f, 0);
            float CurrentBodyAngle3 = BodyTransform.localEulerAngles.z < 180? BodyTransform.localEulerAngles.z: BodyTransform.localEulerAngles.z - 360;
            lineRenderer.SetPosition(0, BodyTransform.position + new Vector3(-mpc_4.BodyPosition[0] * Mathf.Sin(CurrentBodyAngle3 * DegToRad), mpc_4.BodyPosition[0] * Mathf.Cos(CurrentBodyAngle3 * DegToRad), -1f));
            for (int i = 1; i < PredictionTime; i++)
            {
                PredictivePositionIndicaterTransform[i].position = BodyTransform.position + new Vector3(-mpc_4.BodyPosition[i] * Mathf.Sin(CurrentBodyAngle3 * DegToRad), mpc_4.BodyPosition[i] * Mathf.Cos(CurrentBodyAngle3 * DegToRad), -1f);
                PositionIndicaterPosition[i] = new Vector3(PredictivePositionIndicaterTransform[i].position.x, PredictivePositionIndicaterTransform[i].position.y, -0.9f);
                lineRenderer.SetPosition(i, PositionIndicaterPosition[i]);
            }
            rb.AddForce(new Vector2((LeftPower + RightPower) * Mathf.Sin(-CurrentBodyAngle3 * DegToRad), (LeftPower + RightPower) * Mathf.Cos(CurrentBodyAngle3 * DegToRad)));
            rb.AddTorque(TorqueConstant * (mpc_4.RightForce - mpc_4.LeftForce));
            break;

        default:
            break;
        }
    }
コード例 #6
0
ファイル: HorseMovement.cs プロジェクト: HjorturJ/Horse
    void FixedUpdate()
    {
        if (firstTimer > maxTime || secondTimer > maxTime || thirdTimer > maxTime ||
            fourthTimer > maxTime || fifthTimer > maxTime || sixthTimer > maxTime)
        {
            resetTimers();
        }

        if (isFirstRunning)
        {
            firstTimer += Time.deltaTime;
        }
        if (isSecondRunning)
        {
            secondTimer += Time.deltaTime;
        }
        if (isThirdRunning)
        {
            thirdTimer += Time.deltaTime;
        }

        if (isFourthRunning)
        {
            fourthTimer += Time.deltaTime;
        }
        if (isFifthRunning)
        {
            fifthTimer += Time.deltaTime;
        }
        if (isSixthRunning)
        {
            sixthTimer += Time.deltaTime;
        }

        if (Input.GetKeyDown(KeyCode.L))
        {
            isFirstRunning = true;
        }

        if (Input.GetKeyDown(KeyCode.A))
        {
            isFourthRunning = true;
        }

        if (Input.GetKeyDown(KeyCode.K) && isFirstRunning)
        {
            isSecondRunning = true;
        }

        if (Input.GetKeyDown(KeyCode.S) && isFourthRunning)
        {
            isFifthRunning = true;
        }

        if (Input.GetKeyDown(KeyCode.J) && isSecondRunning)
        {
            isThirdRunning = true;
        }

        if (Input.GetKeyDown(KeyCode.D) && isFifthRunning)
        {
            isSixthRunning = true;
        }

        if (isFirstRunning && isThirdRunning && !isSecondRunning)
        {
            resetTimers();
        }
        if (isFourthRunning && isSixthRunning && !isFifthRunning)
        {
            resetTimers();
        }

        if (Input.GetKeyDown(KeyCode.L) && (Input.GetKeyDown(KeyCode.J) || Input.GetKeyDown(KeyCode.K) || Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.D)))
        {
            resetTimers();
        }

        if (Input.GetKeyDown(KeyCode.A) && (Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.K) || Input.GetKeyDown(KeyCode.J)))
        {
            resetTimers();
        }


        if (isThirdRunning && isSixthRunning)
        {
            rhythm = true;
            StartCoroutine(RhythmFalloff());
        }

        if (rhythm)
        {
            body.constraints = RigidbodyConstraints2D.FreezeRotation;
            body.AddForce(new Vector2(5f, 0.2f) * 100, ForceMode2D.Force);
            FrontFrontLeg.AddTorque(buttonPower, ForceMode2D.Force);
            FrontBackLeg.AddTorque(buttonPower, ForceMode2D.Force);
            BackFrontLeg.AddTorque(buttonPower, ForceMode2D.Force);
            BackBackLeg.AddTorque(buttonPower, ForceMode2D.Force);
        }
        else
        {
            body.constraints = RigidbodyConstraints2D.None;
            if (Input.GetKeyDown(KeyCode.L))
            {
                FrontFrontLeg.AddTorque(buttonPower * 0.1f, ForceMode2D.Impulse);
            }

            if (Input.GetKeyDown(KeyCode.K))
            {
                FrontBackLeg.AddTorque(buttonPower * 0.1f, ForceMode2D.Impulse);
            }

            if (Input.GetKeyDown(KeyCode.J))
            {
                FrontFrontLegLower.AddTorque(-50f, ForceMode2D.Impulse);
                FrontBackLegLower.AddTorque(-50f, ForceMode2D.Impulse);
            }


            if (Input.GetKeyDown(KeyCode.A))
            {
                BackFrontLeg.AddTorque(buttonPower * 0.1f, ForceMode2D.Impulse);
            }

            if (Input.GetKeyDown(KeyCode.S))
            {
                BackBackLeg.AddTorque(buttonPower * 0.1f, ForceMode2D.Impulse);
            }

            if (Input.GetKeyDown(KeyCode.D))
            {
                BackFrontLegLower.AddTorque(-50f, ForceMode2D.Impulse);
                BackBackLegLower.AddTorque(-50f, ForceMode2D.Impulse);
            }
        }
    }
コード例 #7
0
 /// <summary>
 /// When the APC is ready to stop, it will gradually slow it's velocity until completely stopped.
 /// Will then execute the Deploy Order.
 /// </summary>
 /// <see cref="DeployOrder"/>
 private void StopOrder()
 {
     _myRigidBody.AddTorque(torque);
     _myRigidBody.drag        = drag;
     _myRigidBody.angularDrag = angularDrag;
 }
コード例 #8
0
        private void CheckDirection()
        {
            m_secondTouchPos   = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
            m_secondTouchPos.x = m_firstTouchPos.x - 2.5f;//test code
            m_currentSwipe     = new Vector2(m_secondTouchPos.x - m_firstTouchPos.x, m_secondTouchPos.y - m_firstTouchPos.y);
            m_currentSwipe.Normalize();

            if (m_currentSwipe.y > 0.0f)
            {
                float angle = Vector2.Angle(m_currentSwipe, transform.right * -1);
                Debug.Log("angle:" + angle);
                if (30.0f <= angle && angle <= 150.0f)
                {
                    if (m_lastMode != (int)GAMEMODE.BOUNCE)
                    {
                        m_currentBallRigid2D.AddForceAtPosition(
                            m_currentSwipe * m_forceThrowBall, m_currentBall.transform.position, ForceMode2D.Impulse);

                        m_currentBallCollider.enabled = false;
                    }
                    else
                    {
                        Vector2 direction  = Vector2.zero;
                        float   bonusForce = 0.0f;

                        SetDirection(ref direction, ref angle, ref bonusForce);

                        if (direction == Vector2.zero)
                        {
                            m_currentBallRigid2D.AddForceAtPosition(
                                m_currentSwipe * m_forceThrowBall, m_currentBall.transform.position, ForceMode2D.Impulse);
                        }
                        else
                        {
                            m_currentBallRigid2D.AddForceAtPosition(
                                direction * (m_forceThrowBall + bonusForce), m_currentBall.transform.position, ForceMode2D.Impulse);
                        }

                        Physics2D.IgnoreLayerCollision(8, 9);
                    }

                    if (m_currentSwipe.x >= 0.0f)
                    {
                        m_forceTorqueBall *= -1.0f;
                    }
                    m_currentBallRigid2D.AddTorque(m_forceTorqueBall, ForceMode2D.Impulse);

                    // Disappear ball shadow
                    m_ballShadow.SetActive(false);

                    m_currentBall.GetComponent <BallScript>().WasThrow = true;
                    m_currentBallAnimation.Play("ball_away");

                    m_scored        = false;
                    m_ballWasThrown = true;
                    GameState       = GAMESTATE.START;

                    if (UIManager._instance.StartMenuShowing)
                    {
                        UIManager._instance.FadeOutStartMenu();
                        UIManager._instance.ScoreSection.SetActive(false);
                    }

                    CurrentScoreTextMesh.gameObject.SetActive(true);

                    if (m_lastMode == (int)GAMEMODE.TIME)
                    {
                        if (!m_runTimer)
                        {
                            m_runTimer = true;
                        }
                    }

                    m_addStar = false;
                    m_throwsCount++;

                    SoundManager._instance.PlaySound(Constants.THROW_SOUND);
                }
            }
        }
コード例 #9
0
    // Update is called once per frame
    void Update()
    {
        if (!GameDirector.Instance.GetPauseFlg)     // ポーズ中でなければ通常通り実行
        {
            // 最初のタップから最後のタップまで座標を取得
            if (GameDirector.Instance.GetArmNumber() > 0 && GameDirector.Instance.GetArmNumber() <= _MAX_TAP + 1)
            {
                TimeCount += Time.deltaTime;                         // 1フレーム間の時間を加算
                if (TimeCount > SavePosTime && i < 100)              // 一定時間経過後
                {
                    TimeCount   = 0;                                 // タイムカウンタをリセット
                    position[i] = this.transform.position;           // 現在の座標を取得
                    angle[i]    = this.transform.localEulerAngles.z; // 現在の角度を取得
                    i++;                                             // 保存する配列の要素番号を1つ加算

                    //------- デバッグ用 -------//
                    Debug.Log(position[i - 1]);
                    //--------------------------//
                }
            }

            if (GameDirector.Instance.GetArmNumber() > 1 && GameDirector.Instance.GetArmNumber() <= _MAX_TAP + 1) // 最初のタップと最後のタップ以外
            {
                Presstime += Time.deltaTime;                                                                      // 長押ししている時間を計測
                if (Presstime > ArrowDisplayTime)                                                                 // 一定時間長押ししたら
                {
                    ArrowObject.SetActive(true);                                                                  // アクティブに設定
                }
            }

            if (Input.GetMouseButtonUp(0) && GameDirector.Instance.GetArmNumber() > 0)                                // 左クリックしたとき、かつタップの最大数以下の時
            {
                Presstime = 0;                                                                                        // 長押しの時間を初期化

                if (GameDirector.Instance.GetArmNumber() <= _MAX_TAP + 1 && GameDirector.Instance.GetArmNumber() > 1) // 最初のタップと最後のタップ以外の時
                {
                    if (i < 100)
                    {
                        TimeCount   = 0;                                 // タイムカウンタをリセット
                        position[i] = this.transform.position;           // 爆発したときも座標を取得
                        angle[i]    = this.transform.localEulerAngles.z; // 現在の角度を取得
                        i++;                                             // 保存する配列の要素番号を1つ加算
                    }
                    if (!ArrowObject.activeSelf)                         // 非アクティブ状態なら
                    {
                        ArrowObject.SetActive(true);                     // アクティブ状態に設定
                    }

                    ArrowObject.GetComponent <ArrowDirector>().SetArrowPos(transform.GetChild(armNum + 1));                   // 次の腕に応じた矢印の位置に設定
                    ArrowObject.SetActive(false);                                                                             // 非アクティブに設定

                    Instantiate(ParticleList[(int)PARTICLE.ARM], transform);                                                  // 海星の子に設定して泡のパーティクルを生成
                    Vector2 armPos = transform.GetChild(armNum).position;                                                     // ヒエラルキービューの上から子オブジェクトのワールド座標を取得
                    ForceX = transform.position.x - armPos.x;                                                                 // 本体と腕のx座標の差を求める(力を加えるx方向)
                    ForceY = transform.position.y - armPos.y;                                                                 // 本体と腕のy座標の差を求める(力を加えるy方向)

                    Rigidbody2D rb    = GetComponent <Rigidbody2D>();                                                         // Rigidbodyを取得
                    Vector2     force = new Vector2(ForceX * bombPower, ForceY * bombPower);                                  // 本体と腕の座標の差から力を設定

                    rb.angularVelocity = 0;                                                                                   // 回転の力を0に戻す

                    if (transform.position.x < armPos.x)                                                                      // 腕が本体の右側にあれば
                    {
                        rb.AddTorque(1.5f, ForceMode2D.Impulse);                                                              // 時計回りに回転
                    }
                    else                                                                                                      // そうでなければ
                    {
                        rb.AddTorque(-1.5f, ForceMode2D.Impulse);                                                             // 反時計回りに回転
                    }
                    rb.AddForce(force, ForceMode2D.Impulse);                                                                  // 一瞬のみ力を加える

                    LegSpriteRenderer[armNum].sprite = LegImages[2];                                                          // 現在の腕を爆発後の腕の画像に変更
                    transform.GetChild(armNum).GetComponent <Transform>().localScale = new Vector3(1.0f, 1.0f, 1.0f);         // 現在の腕の大きさを標準に変更

                    if (armNum < _MAX_LEG - 1)                                                                                // 現在の腕が最後の腕じゃなかったら
                    {
                        transform.GetChild(armNum + 1).GetComponent <Transform>().localScale = new Vector3(1.5f, 1.5f, 1.5f); // 次の腕の大きさを1.5倍に変更
                        LegSpriteRenderer[armNum + 1].sprite = LegImages[1];                                                  // 次の腕を選択時の腕の画像に変更
                    }

                    armNum++;                                                                                    // 次の腕へ
                    GameDirector.Instance.SetArmNumber(GameDirector.Instance.GetArmNumber() - 1);                // 腕の本数を1減算
                }
                else if (GameDirector.Instance.GetArmNumber() > _MAX_TAP)                                        // 最初のタップ
                {
                    Rigidbody2D rb    = GetComponent <Rigidbody2D>();                                            // Rigidbodyを取得
                    Vector2     force = new Vector2(-5.0f * bombPower / 20, 5.0f * bombPower / 20);              // 力を設定
                    rb.AddTorque(0.8f, ForceMode2D.Impulse);                                                     // 一瞬のみ回転を加える
                    rb.AddForce(force, ForceMode2D.Impulse);                                                     // 一瞬のみ力を加える

                    transform.GetChild(0).GetComponent <Transform>().localScale = new Vector3(1.5f, 1.5f, 1.5f); // 最初の腕の表示を1.5倍に拡大
                    LegSpriteRenderer[0].sprite = LegImages[1];                                                  // 最初の腕を選択時の腕に画像を変更

                    GameDirector.Instance.SetArmNumber(GameDirector.Instance.GetArmNumber() - 1);                // 腕の本数を1減算
                }
                else                                                                                             // 最後の花火
                {
                    Instantiate(ParticleList[(int)PARTICLE.FIREWORK], transform);                                // 海星の子に設定して花火のパーティクルを設定
                    SaveCSV SavePos = this.GetComponent <SaveCSV>();                                             // スクリプトを取得
                    //SavePos.SavePos(position, angle, i);                            // 取得した座標をCSVファイルに書き込み
                    SavePos.BinarySavePos(position, angle, i);                                                   // 取得した座標と角度をCSVファイルに書き込み
                    StartCoroutine("DestroyObject");                                                             //1フレーム後に自分自身を破棄
                }
            }
        }
    }
コード例 #10
0
    } // Called automatically Every Frame

    // To use a rigidbody (physics) use Fixed Update
    // Called automatically every physics frame (about 3-4x faster then Update). All Physics related things need to be in here.
    private void FixedUpdate()
    {
        rigid.AddForce(new Vector2(1f, 0)); // add a force to a given vector, doesn't need to be normalized with Time.deltaTime
        rigid.AddTorque(1f);                // add rotational force (torque) //note these are for 2d, if you use 3d rigidbody you need to use a Vector3 instead
    }
コード例 #11
0
    // Update is called once per frame
    void FixedUpdate()
    {
        // If tank is dead, then set to dead colour
        if (state == TankState.dead)
        {
            colour = new Color(1.0f, 1.0f, 1.0f, 1.0f);
            spriteRenderer.color = Color.gray;
            return;
        }

        float dt     = Time.fixedDeltaTime;
        float t      = Time.time;
        float torque = 0.0f;
        float accel  = 0.0f;

        angle = Mathf.Deg2Rad * transform.rotation.eulerAngles.z;
        Vector3 dir = new Vector3(Mathf.Cos(angle), Mathf.Sin(angle), 0.0f);

        // Compute torques
        if (Input.GetKey(leftKey))
        {
            torque = maxTorque;
        }
        else if (Input.GetKey(rightKey))
        {
            torque = -maxTorque;
        }
        else
        {
            torque = 0.0f;
        }

        // Compute forward
        if (Input.GetKey(forwardKey))
        {
            accel = maxAccel;
        }
        else if (Input.GetKey(backwardKey))
        {
            accel = -maxAccel;
        }
        else
        {
            accel = 0.0f;
        }

        // Compute force to drive tank forward
        Vector3 force = accel * dir;

        // Only allow a torque to rotate the tank when the tank is moving
        torque = accel * torque;

        // Finally add force/torque to Rigid body
        rb.AddForce(force);
        rb.AddTorque(torque);

        // Make tank visible if canon is fired
        if (t - tFire > fireDelay && Input.GetKey(fireKey))
        {
            alphaLevel = 1.0f;
            tFire      = t;

            // Create projectile instance
            Instantiate(ProjectilePrototypes.FirstOrDefault(it => it.Type == CurrentProjectile).Prefab,
                        transform.position + canonLength * dir,
                        transform.rotation);
        }

        // After initial visible time, fade tank
        if (t > timeVisibleInit)
        {
            alphaLevel -= fadeRate * dt;
        }
        alphaLevel           = Mathf.Max(0.0f, alphaLevel);
        spriteRenderer.color = new Color(colour.r, colour.g, colour.b, alphaLevel);

        Hitable HitableComp = gameObject.GetComponent <Hitable>();
        Color   HC          = HitableComp.ShieldHalo.color;

        if (HitableComp.shield < 100)
        {
            HC.a = HitableComp.shield;
        }
        if (HitableComp.shield >= 100)
        {
            HC.a = 100;
        }
        if (HitableComp.shield < 1)
        {
            HC.a = 0;
        }
        if (HC.a > alphaLevel)
        {
            HC.a = alphaLevel;
        }

        HitableComp.ShieldHalo.color = HC;

        if (alphaLevel < 1)
        {
            HitableComp.enabled = false;
        }
        else
        {
            HitableComp.enabled = true;
        }
    }
コード例 #12
0
    private void LateUpdate()
    {
        Vector3 force = Vector3.zero;

        if (Input.GetKey(KeyCode.UpArrow))
        {
            force = _transform.up * moveForce;
            force = new Vector3(force.x, force.y, 0);
            Move(force, _transform.position);
            //mainNozzle.Play();
            downNozzle1.Play();
            downNozzle2.Play();
        }
        if (Input.GetKey(KeyCode.DownArrow))
        {
            force = -_transform.up * moveForce;
            force = new Vector3(force.x, force.y, 0);
            Move(force, _transform.position);
            //mainNozzle.Play();
            upNozzle1.Play();
            upNozzle2.Play();
        }

        if (Input.GetKey(KeyCode.LeftArrow))
        {
            //force = _transform.up * rotationForce;
            _rigidBody.AddTorque(rotationForce, ForceMode2D.Force);
        }
        else if (Input.GetKey(KeyCode.RightArrow))
        {
            //force = -_transform.up * rotationForce;
            _rigidBody.AddTorque(-rotationForce, ForceMode2D.Force);
        }

        //For rope
        //if (Input.GetKeyDown(KeyCode.Q) && rope != null)
        //{
        //    rope.DestroyRope(_transform.up);
        //    rope = null;
        //}
        //if (Input.GetKeyDown(KeyCode.E) && rope == null)
        //{
        //    print("shoot");
        //    GameObject ropeObj = Instantiate(ropePrefab, _transform);
        //    rope = ropeObj.GetComponent<Rope>();
        //    rope.Setup(_rigidBody, -_transform.up * shootForce);
        //}
        //For gravity ray
        if (Input.GetKeyDown(KeyCode.Q) && dockingMethod != null)
        {
            dockingMethod.DestroyObject();
            dockingMethod = null;
        }
        if (Input.GetKeyDown(KeyCode.E) && dockingMethod == null)
        {
            GameObject dockingMethodObj = Instantiate(dockingMethodPrefab, _transform);
            dockingMethod = dockingMethodObj.GetComponent <IDockingMethod>();
            dockingMethod.Setup(gameObject, dockingMethodPrefab.transform.localPosition);
        }

        if (Input.GetKeyDown(KeyCode.Escape))
        {
            EscEvent();
        }

        if (Input.GetKeyUp(KeyCode.UpArrow))
        {
            //mainNozzle.Stop();
            downNozzle1.Stop();
            downNozzle2.Stop();
        }
        if (Input.GetKeyUp(KeyCode.DownArrow))
        {
            upNozzle1.Stop();
            upNozzle2.Stop();
        }
        if (Input.GetKeyUp(KeyCode.LeftArrow))
        {
            downNozzle1.Stop();
        }
        if (Input.GetKeyUp(KeyCode.RightArrow))
        {
            downNozzle2.Stop();
        }
        //Move deceleration
        if (!isInGravity && !Input.GetKey(KeyCode.UpArrow) && !Input.GetKeyDown(KeyCode.UpArrow) && !Input.GetKeyUp(KeyCode.UpArrow) && _rigidBody.velocity.magnitude > 0)
        {
            if (_rigidBody.velocity.magnitude < 0.1f)
            {
                _rigidBody.velocity = Vector2.zero;
                AngularDeveleration();
                return;
            }
            force = -_rigidBody.velocity.normalized * moveDeceleration;
            force = new Vector3(force.x, force.y, 0);
            Move(force, _transform.position);
        }
        else if (!isInGravity && !Input.GetKey(KeyCode.DownArrow) && !Input.GetKeyDown(KeyCode.DownArrow) && !Input.GetKeyUp(KeyCode.DownArrow) && _rigidBody.velocity.magnitude > 0)
        {
            if (_rigidBody.velocity.magnitude < 0.1f)
            {
                _rigidBody.velocity = Vector2.zero;
                AngularDeveleration();
                return;
            }
            force = -_rigidBody.velocity.normalized * moveDeceleration;
            force = new Vector3(force.x, force.y, 0);
            Move(force, _transform.position);
        }
        //Rotate deceleration
        AngularDeveleration();
    }
コード例 #13
0
    private void AddRandomTorque()
    {
        float torque = Random.Range(-maxTorque, maxTorque);

        rigidbody.AddTorque(torque);
    }
コード例 #14
0
    // Update is called once per frame
    public bool Launch(Cinemachine.CinemachineVirtualCamera fCam, Vector3 dir, bool manualTorque = false, float torqueAmount = 0f)
    {
        if (!isAlive)
        {
            return(false);
        }

        if (!firstJump && !jumper)
        {
            return(false);
        }

        if (!firstJump && !isAttached && !isGrabbed)
        {
            return(false);
        }

        isAttached = false;

        activatedBlocks.ForEach(b => b.Deactivate());
        activatedBlocks.Clear();

        grabbers.ForEach(g => g.Detach());

        followCam = fCam;
        followCam.gameObject.SetActive(true);
        followCam.Follow = body.transform;

        body.bodyType = RigidbodyType2D.Dynamic;
        limbs.ToList().ForEach(l => l.bodyType = RigidbodyType2D.Dynamic);

        line.enabled = false;

        body.AddForce(dir * 150f, ForceMode2D.Impulse);

        if (activatedBlocks.Any())
        {
            activatedBlocks.ForEach(b => b.Deactivate());
        }

        if (firstJump)
        {
            var amt = manualTorque ? torqueAmount * 3000f : dir.x * 100f;
            body.AddTorque(amt, ForceMode2D.Impulse);
            cam.BaseEffect(1.1f);

            AudioManager.Instance.PlayEffectAt(32, transform.position, 2f);
            AudioManager.Instance.PlayEffectAt(29, transform.position, 0.489f);
            AudioManager.Instance.PlayEffectAt(47, transform.position, 0.852f);
            AudioManager.Instance.PlayEffectAt(49, transform.position, 1f);
        }

        AudioManager.Instance.PlayEffectAt(31, transform.position, 0.723f);
        AudioManager.Instance.PlayEffectAt(25, transform.position, 1.104f);
        AudioManager.Instance.PlayEffectAt(37, transform.position, 1.241f);
        AudioManager.Instance.PlayEffectAt(40, transform.position, 1f);
        AudioManager.Instance.PlayEffectAt(42, transform.position, 0.643f);

        hands.ToList().ForEach(h => h.AddForce(dir * Random.Range(5f, 10f), ForceMode2D.Impulse));

        var ret = firstJump;

        firstJump = false;

        return(ret);
    }
コード例 #15
0
    // Use this for initialization
    void Start()
    {
        Rigidbody2D r2d = this.GetComponent <Rigidbody2D> ();

        r2d.AddTorque(Random.Range(-50.0f, 50.0f));
    }
コード例 #16
0
ファイル: Drifting.cs プロジェクト: magelon/drifting
    void Update()
    {
        //when has ability turning left
        if (turnleft)
        {
            //show turn left sign
            sr.rectTransform.localScale = new Vector3(1, 1, 1);
        }
        else
        {
            //flip the sign
            sr.rectTransform.localScale = new Vector3(-1, 1, 1);
        }
        //velocityLimit = rb.velocity.magnitude;
        //transform.Translate(transform.up*0.01f);

        //start drifting
        if (Input.GetMouseButton(0))
        {
            //decresing velocity
            accelerate = false;

            //add turning force
            if (turnleft)
            {
                rb.AddTorque(2f);
            }
            else
            {
                rb.AddTorque(-2f);
            }

            //start counting turning timer
            timerun += 1;

            //play the drifting sound
            if (!audioData.isPlaying)
            {
                audioData.Play(0);
            }

            //play the smoke partical effect
            if (!par.isPlaying)
            {
                par.Play();
            }
        }

        //stop drifting
        if (Input.GetMouseButtonUp(0))
        {
            rb.AddForce(transform.up * 0.3f);
            //incresing velocity
            accelerate = true;
            //stop turining force
            rb.angularVelocity = 0;
            //stop drifting sound
            audioData.Stop();

            if (timerun > 35)
            {
                //stop velocity and then start accelerating
                StartCoroutine(stopDely());
            }

            //reset timer
            timerun = 0;
        }
    }
コード例 #17
0
    private void Update()
    {
        //MOVE THIS OPTHER TIME
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            scaleFactorVal  += 1;
            scaleFactor.text = "(arrowsupdown)ScaleFactor: " + scaleFactorVal.ToString();
        }
        if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            scaleFactorVal -= 1;
            if (scaleFactorVal < 1)
            {
                scaleFactorVal = 1;
            }
            scaleFactor.text = "(arrowsupdown)ScaleFactor: " + scaleFactorVal.ToString();
        }

        //scale stuff
        transform.localScale = new Vector3(scaleFactorVal, scaleFactorVal, 1);
        for (int i = 0; i < avoidanceVectors.Length; i++)
        {
            avoidanceVectors[i] = oldavoidanceVectors[i] * scaleFactorVal;
        }
        raycastDownLengthJump = oldraycastDownLengthJump * scaleFactorVal;
        raycastDownLengthWalk = oldraycastDownLengthWalk * scaleFactorVal;


        if (!movementMode.isOn)
        {
            //avoidance stuff
            centerRotated  = center.x * transform.right + center.y * transform.up;
            centerPosition = transform.position + centerRotated;
            //rotate avoidance vectors
            for (int i = 0; i < avoidanceVectors.Length; i++)
            {
                avoidanceVectorsRotated[i] = Rotated(avoidanceVectors[i], transform.rotation, new Vector3(0, 0, 0));
            }

            for (int i = 0; i < avoidanceVectors.Length; i++)
            {
                RaycastHit2D[] hit      = Physics2D.RaycastAll(centerPosition, avoidanceVectorsRotated[i], avoidanceVectorsRotated[i].magnitude);
                Color          yesColor = Color.green;
                if (hit.Length > 1)
                {
                    yesColor = Color.red;
                    if (i == 0)
                    {
                        thisRigidbody.AddTorque(antiFallForce);
                    }
                    if (i == 1)
                    {
                        thisRigidbody.AddTorque(antiFallForce * -1);
                    }
                }

                Debug.DrawLine(centerPosition, centerPosition + avoidanceVectorsRotated[i], yesColor);
            }
        }

        //check if change jetpack or no
        //doing in updaet to not miss clicks
        if (Input.GetKeyDown(KeyCode.C))
        {
            movementMode.isOn = !movementMode.isOn;
        }
        //MOVE ALL THIS SHTI TO SEPERATE SHIT TO AVOID CONFUSION LATER GUT FOR NOW WHO CARES
        if (Input.GetKeyDown(KeyCode.V))
        {
            drawSceneGravityRadiobutton.isOn = !drawSceneGravityRadiobutton.isOn;
        }

        //zoom scroll on camera
        //is 1 or -1 for each click on mouse
        cameraZoomSizeValue += cameraZoomSpeed * -Input.mouseScrollDelta.y;
        if (cameraZoomSizeValue < cameraSizeMinMax.x)
        {
            cameraZoomSizeValue = cameraSizeMinMax.x;
        }
        else if (cameraZoomSizeValue > cameraSizeMinMax.y)
        {
            cameraZoomSizeValue = cameraSizeMinMax.y;
        }

        Camera.main.orthographicSize = cameraZoomSizeValue;
    }
コード例 #18
0
 public void TurnLeft(float deltaTime)
 {
     _rigidBody.AddTorque(_leftRightSpeed * deltaTime, ForceMode2D.Impulse);
 }
コード例 #19
0
    void handleControls()
    {
        bool holdingLeft    = Input.GetKey(App.ROTATE_LEFT_KEY);
        bool holdingRight   = Input.GetKey(App.ROTATE_RIGHT_KEY);
        bool holdingGas     = Input.GetKey(App.ACCELERATE_KEY);
        bool holdingReverse = Input.GetKey(App.DECERATE_KEY);

        Direction direction = Direction.none;

        if (holdingLeft && !holdingRight)
        {
            direction = Direction.left;
        }
        else if (holdingRight && !holdingLeft)
        {
            direction = Direction.right;
        }

        Gas gas = Gas.none;

        if (holdingGas && !holdingReverse)
        {
            gas = Gas.forward;
        }
        else if (holdingReverse && !holdingGas)
        {
            gas = Gas.back;
        }

        if (direction == Direction.left)
        {
            body.AddTorque(Mathf.Clamp(15 * (maxAngularVelocity - body.angularVelocity), 0, 15));
        }
        else if (direction == Direction.right)
        {
            body.AddTorque(Mathf.Clamp(15 * (-maxAngularVelocity - body.angularVelocity), -15, 0));
        }

        if (gas == Gas.forward)
        {
            float forwardVel = transform.InverseTransformDirection(body.velocity).y;
            body.AddRelativeForce(Vector2.up * thrustFactor * Mathf.Lerp(1, 5, -forwardVel / 2.0f));
        }
        else if (gas == Gas.back)
        {
            float forwardVel = transform.InverseTransformDirection(body.velocity).y;
            body.AddRelativeForce(Vector2.up * -thrustFactor * Mathf.Lerp(1, 5, forwardVel / 2.0f));
        }

        if (Input.GetKey(App.BRAKE_KEY))
        {
            body.drag        = 0.8f;
            body.angularDrag = 0.8f;
        }
        else
        {
            body.drag        = 0f;
            body.angularDrag = 0f;
        }

        foreach (var thruster in thrusters)
        {
            thruster.script.setEmitFlames(gas, direction);
        }
    }
コード例 #20
0
    private void LateUpdate()
    {
        Vector3 force         = Vector3.zero;
        float   horizontalAxe = InputController.Instance.HorizontalAxe;
        float   verticalAxe   = InputController.Instance.VerticalAxe;
        float   brake         = InputController.Instance.Space;

        if (verticalAxe != 0 && fuelSystem.HaveFuel())
        {
            fuelSystem.ConsumeFuel(Mathf.Abs(verticalAxe));
            force = _transform.up * moveForce * verticalAxe;
            force = new Vector3(force.x, force.y, 0);
            Move(force, _transform.position);
        }
        if (horizontalAxe < 0 && _rigidBody.angularVelocity <= maxAngularVelocity)
        {
            _rigidBody.AddTorque(-rotationForce * horizontalAxe, ForceMode2D.Force);
        }
        else if (horizontalAxe > 0 && _rigidBody.angularVelocity >= -maxAngularVelocity)
        {
            _rigidBody.AddTorque(-rotationForce * horizontalAxe, ForceMode2D.Force);
        }

        //For gravity ray
        if (InputController.Instance.KeyE)
        {
            if (dockingMethod == null)
            {
                GameObject dockingMethodObj = Instantiate(dockingMethodPrefab, _transform);
                dockingMethod = dockingMethodObj.GetComponent <IDockingMethod>();
                dockingMethod.Setup(gameObject, dockingMethodPrefab.transform.localPosition);
            }
            else
            {
                dockingMethod.DestroyObject();
                dockingMethod = null;
            }
        }

        //Brake
        if (brake >= .01f && fuelSystem.HaveFuel())
        {
            fuelSystem.ConsumeFuel(Mathf.Abs(brake));
            MoveDeceleration(horizontalAxe, angularDeceleration, verticalAxe, brakeForce * brake);
        }

        if (InputController.Instance.Cancel)
        {
            EscEvent();
        }

        //Engines Animations
        if (fuelSystem.HaveFuel())
        {
            //if (Mathf.Abs(verticalAxe) >= .01f)
            EngineAnimations(verticalAxe);
            if (brake >= .01f)
            {
                EngineAnimations(-brake);
            }
        }
        else
        {
            EngineAnimations(0);
        }

        //Move deceleration
        if (!isInGravity /* && _rigidBody.velocity.magnitude > 0*/)
        {
            MoveDeceleration(horizontalAxe, angularDeceleration, verticalAxe, moveDeceleration);
            //if (verticalAxe == 0/* && horizontalAxe == 0*/)
            //{
            //    if (_rigidBody.velocity.magnitude < 0.1f)
            //    {
            //        _rigidBody.velocity = Vector2.zero;
            //        AngularDeveleration(horizontalAxe, angularDeceleration);
            //        return;
            //    }
            //    force = -_rigidBody.velocity.normalized * moveDeceleration;
            //    force = new Vector3(force.x, force.y, 0);
            //    Move(force, _transform.position);
            //}
        }

        //Rotate deceleration
        AngularDeceleration(horizontalAxe, angularDeceleration);
    }
コード例 #21
0
    // Use this for initialization

    private void OnCollisionEnter2D(Collision2D col)
    {
        if (col.collider.name == "Gold(Clone)" && transform.parent.name == "Kart(Clone)" && able == true)
        {
            if (col.gameObject.GetComponentInChildren <Text>().text == Word.Word)
            {
                AudioClips.Source.clip = AudioClips.GoodAnswer;
                AudioClips.Source.Play();
                AudioClips.SecondSource.clip = AudioClips.OnGround;
                AudioClips.SecondSource.Play();
                Bands.RemoveAll();
                able = false;
                col.gameObject.GetComponent <Rigidbody2D>().simulated = false;
                KartsScript.VictoryPoints++;
                if (KartsScript.VictoryPoints == 4)
                {
                    Victory();
                }
            }
            else if (Word.Justwords.Length == 1 && col.gameObject.GetComponentInChildren <Text>().text == Word.Justwords[0])
            {
                AudioClips.Source.clip = AudioClips.GoodAnswer;
                AudioClips.Source.Play();
                AudioClips.SecondSource.clip = AudioClips.OnGround;
                AudioClips.SecondSource.Play();
                Bands.RemoveAll();
                able = false;
                col.gameObject.GetComponent <Rigidbody2D>().simulated = false;
                KartsScript.VictoryPoints++;
                if (KartsScript.VictoryPoints == 4)
                {
                    Victory();
                }
            }
            else if (Word.Justwords.Length == 2 && col.gameObject.GetComponentInChildren <Text>().text == Word.Justwords[1])
            {
                AudioClips.Source.clip = AudioClips.GoodAnswer;
                AudioClips.Source.Play();
                AudioClips.SecondSource.clip = AudioClips.OnGround;
                AudioClips.SecondSource.Play();
                Bands.RemoveAll();
                able = false;
                col.gameObject.GetComponent <Rigidbody2D>().simulated = false;
                KartsScript.VictoryPoints++;
                if (KartsScript.VictoryPoints == 4)
                {
                    Victory();
                }
            }
            else
            {
                AudioClips.Source.clip = AudioClips.BadAnswer;
                AudioClips.Source.Play();
                GameObject p = col.gameObject;
                Destroy(p.GetComponent <Collider2D>());
                p.transform.Translate(Vector3.up);
                Rigidbody2D rigidbody = p.GetComponent <Rigidbody2D>();
                rigidbody.AddForce((Vector2.up * 2 + Vector2.left) * 125);
                rigidbody.AddTorque(35);
                rigidbody.gravityScale = 1;
            }
            GoldBLockSpawner.SpawnGold(0);
        }
    }
コード例 #22
0
 void Start()
 {
     rb_2d = transform.GetComponent <Rigidbody2D>();
     rb_2d.AddForce(new Vector2(10f, 10f), ForceMode2D.Impulse);
     rb_2d.AddTorque(10, ForceMode2D.Force);
 }
コード例 #23
0
 void setNewTorque()
 {
     torqueMagnitude = Random.Range(1500.0f, -1500.0f);
     body2d.AddTorque(torqueMagnitude * Time.deltaTime);
 }
コード例 #24
0
 void Move(float moveHorizontal)
 {
     rb2D.AddForce(new Vector2(moveHorizontal * acceleration, 0));
     rb2D.AddTorque(-moveHorizontal * angularForce);
 }
コード例 #25
0
ファイル: DrivingScript.cs プロジェクト: Tekknobot/driving3d
    void FixedUpdate()
    {
        float acc   = 0;
        float steer = 0;
        float brake = 0;

        if (playerControlled)
        {
            acc   = Input.GetAxisRaw("Vertical");               // up: 1, down: -1
            steer = Input.GetAxisRaw("Horizontal");             // left: -1, right: 1
            brake = Input.GetAxisRaw("Handbrake");
        }
        else if (ai != null)
        {
            DrivingActions actions = ai.GetDrivingActions();
            acc   = actions.acc;
            steer = actions.steer;
        }

        bool movingForward = Vector2.Dot(body.velocity, transform.up) > 0;

        // get the engine force for each powered wheel
        float engine = 0;

        if (acc > 0)
        {
            engine = engineAcc * acc;
        }
        else if (acc < 0)
        {
            engine = (movingForward ? engineBrk : engineRev) * acc;
        }

        steerDir += Mathf.Clamp((steer * maxWheelAngle) - steerDir,
                                -wheelAngleVelocity, wheelAngleVelocity);

        foreach (Wheel wheel in wheels)
        {
            Rigidbody2D wheelBody = wheel.obj.GetComponent <Rigidbody2D>();

            // set the rotation(angle) for the rotatable wheels
            if (wheel.rotatable)
            {
                float currentAngle = GetCurrentAngle(wheel.obj.transform);
                float angleDiff    = steerDir - currentAngle;

                HingeJoint2D joint = wheel.obj.GetComponent <HingeJoint2D>();
                JointMotor2D motor = joint.motor;
                if (Mathf.Abs(angleDiff) > .01)
                {
                    motor.motorSpeed = wheelMotorSpeed * Mathf.Sign(angleDiff);
                    joint.motor      = motor;
                }
                else if (motor.motorSpeed != 0)
                {
                    motor.motorSpeed = 0;
                    joint.motor      = motor;
                }
                // wheel.transform.Rotate(new Vector3(0, 0, currentAngle - steerDir));

                // prevent random wheel joint physics
                wheelBody.angularVelocity = 0;
            }

            // apply engine force
            if (wheel.powered)
            {
                wheelBody.AddRelativeForce(new Vector2(0, engine));
            }

            Vector2 localWheelVelocity = transform.InverseTransformVector(wheelBody.velocity);

            // add rolling resistance
            Vector2 rollingVector = new Vector2(0, localWheelVelocity.y) * -rollingResistance;
            body.AddRelativeForce(rollingVector);
            // drawVector(wheel.transform, transform.rotation * rollingVector, Color.red);

            // add handbrake resistance
            if (brake == 1 && wheel.handbrake)
            {
                Vector2 brakeVector = new Vector2(0, localWheelVelocity.y) * -brakeResistance;
                wheelBody.AddRelativeForce(brakeVector);
                // drawVector(wheel.transform, transform.rotation * brakeVector, Color.magenta);
            }

            // kill sideways speed of wheel
            KillSidewaysSpeed(wheel.obj);
        }

        // kill sideways speed of car
        KillSidewaysSpeed(gameObject);

        // add extra torque when steering, to make up for angular drag
        float torque = (movingForward ? -1 : 1) * steer *
                       (Mathf.Min(steerTorque * body.velocity.magnitude, maxSteerTorque) +
                        (brake * brakeTorque * body.velocity.magnitude));

        body.AddTorque(torque);

        // prevent excess sliding
        if (body.velocity.magnitude <= 0.2 && acc == 0)
        {
            body.velocity = Vector2.zero;
        }

        // angular friction when not steering
        if (steerDir == 0)
        {
            body.angularVelocity -= Mathf.Sign(body.angularVelocity) * torqueDamp;
        }

        // add air resistance
        Vector2 airVector = body.velocity * body.velocity.magnitude * -airResistance;

        body.AddForce(airVector);
        // drawVector(transform, airVector, Color.blue);

        // Debug.Log(body.velocity.magnitude);
        // drawVector(transform, body.velocity, Color.green);
    }
コード例 #26
0
    // Update is called once per frame
    void Update()
    {
        if (gameObject.GetComponent <Rigidbody2D>().velocity.y < -25 && !audioSource.isPlaying)
        {
            audioSource.PlayOneShot(wilhelmScream, 0.25f);
        }

        if (!dudeIsAlive)
        {
            ChangeSprite();
        }

        if (Input.GetKeyDown(KeyCode.R) && !disableThrow)
        {
            Debug.Log(disableThrow);
            dudeIsAlive = !dudeIsAlive;
            ChangeSprite();
        }

        if (Input.GetButton("Fire1") && !disableThrow)
        {
            if (currentDynomiteCount == 0 && !audioSource.isPlaying)
            {
                audioSource.PlayOneShot(RandomNoAmmoClip());
            }

            else if (throwState == "Unprepped" && !disableThrow)
            {
                // start a new throw
                StartThrowPrepTime  = DateTime.Now.Ticks;
                TargetThrowPrepTime = DurationThrowPrepTime;
                throwState          = "PrepThrow";

                // spawn m_throwPowerSpriteObject below us as a child of us
                throwMeterInstance = Instantiate(m_throwPowerSpriteObject, transform.position, Quaternion.identity);
                throwMeterInstance.transform.parent    = transform;
                throwMeterInstance.transform.position -= new Vector3(0f, -0.6f, 0f);
            }

            else if (throwState == "PrepThrow" && !disableThrow)
            {
                // continue charging a throw
                CurrentThrowPrepTime = DateTime.Now.Ticks - StartThrowPrepTime;
                CurrentSquashPercent = SinSquashToTargetVal(CurrentThrowPrepTime, TargetThrowPrepTime);
                // color throwMeterInstance's sprite color using mark's insane math combined with m_throwPowerGradient
                float chargeRatio = (float)CurrentThrowPrepTime / TargetThrowPrepTime;
                throwMeterInstance.GetComponent <SpriteRenderer>().color = m_throwPowerGradient.Evaluate(Mathf.Clamp(chargeRatio, 0f, 1f));
                Vector3 scale = throwMeterInstance.transform.localScale;
                Debug.Log(Mathf.Lerp(.4f, 2f, chargeRatio));
                scale.x = Mathf.Lerp(.4f, 2f, chargeRatio);
                throwMeterInstance.transform.localScale = scale;
            }
        }

        if (Input.GetButtonUp("Fire1") && throwState == "PrepThrow" && currentDynomiteCount >= 1 && !disableThrow)
        {
            throwState            = "Unprepped";
            currentDynomiteCount -= 1;
            Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

            Vector2 direction = (Vector2)((mousePos - transform.position));
            direction.Normalize();
            float throwLength = CurrentSquashPercent * maxThrowMagnitude;

            GameObject  dynamite     = Instantiate(projectile, transform.position, Quaternion.identity);
            Rigidbody2D dynamiteBody = dynamite.GetComponent <Rigidbody2D>();
            dynamiteBody.velocity = direction * throwLength;
            // Debug.Log(CurrentSquashPercent);
            // Debug.Log(maxThrowMagnitude);
            // Debug.Log(throwLength);
            Destroy(throwMeterInstance);
            dynamiteBody.AddTorque(UnityEngine.Random.Range(2f, -2f));
            audioSource.PlayOneShot(RandomThrowClip());
        }
    }
コード例 #27
0
    void FixedUpdate()
    {
        rb2d.velocity = new Vector2(Mathf.Sign(rb2d.velocity.x) * Mathf.Min(Mathf.Abs(rb2d.velocity.x), maxVelocityX),
                                    Mathf.Sign(rb2d.velocity.y) * Mathf.Min(Mathf.Abs(rb2d.velocity.y), maxVelocityY));

        isOnGround = IsOnGround();
        //isAgainstSides = IsAgainstSides();
        if (!canJump && isOnGround)
        {
            canJump = true;
        }
        if (rb2d.velocity.y < -2)
        {
            canJump = false;
        }

        if (state == State.Idle && !isOnGround)
        {
            state = State.Jump;
        }

        if (state == State.Jump && isOnGround)
        {
            state = State.Idle;
        }

        if (isOnGround)
        {
            material.friction   = friction;
            rb2d.sharedMaterial = material;
        }
        else
        {
            material.friction   = 0;
            rb2d.sharedMaterial = material;
        }

        if (isJumpPressing)
        {
            if (canJump)
            {
                rb2d.velocity = new Vector2(rb2d.velocity.x, jumpSpeed);
                canJump       = false;
            }
        }

        float rot = (float)(rotationSpeed + Convert.ToInt32(isOnGround) * rotationSpeed * .25);

        if (isLeftPressing)
        {
            rb2d.AddTorque(rot);
            if (rb2d.velocity.x < 0.1f)
            {
                direction = Direction.Left;
            }

            if (!isOnGround)
            {
                if (rb2d.velocity.x > -maxJumpVelocityX)
                {
                    rb2d.velocity = new Vector2(rb2d.velocity.x - horizontalJumpAcceleration, rb2d.velocity.y);
                }
            }
        }
        if (isRightPressing)
        {
            rb2d.AddTorque(-rot);
            if (rb2d.velocity.x > 0.1f)
            {
                direction = Direction.Right;
            }
            if (!isOnGround)
            {
                if (rb2d.velocity.x < maxJumpVelocityX)
                {
                    rb2d.velocity = new Vector2(rb2d.velocity.x + horizontalJumpAcceleration, rb2d.velocity.y);
                }
            }
        }
    }
コード例 #28
0
 void Start()
 {
     rigidbody2D.AddForce((player.transform.position - transform.position).normalized * Random.value * forceMultiplier);
     rigidbody2D.AddTorque((Random.value - 0.5f) * 2f * torqueMultiplier);
 }
コード例 #29
0
    public void Drive(float vert, float rotation)
    {
        if (vert > 1)
        {
            vert = 1;
        }
        else if (vert < -1)
        {
            vert = -1;
        }

        if (rotation > 1)
        {
            rotation = 1;
        }
        else if (rotation < -1)
        {
            rotation = -1;
        }

        // Calculate engineStress (smoothed out engine usage)
        if (engineSound != null)
        {
            engineStress =
                (engineStress * 0.97)
                + (Mathf.Clamp((Mathf.Abs(vert) + Mathf.Abs(rotation * 0.6666f)), 0.3f, 1.0f) * 0.03);
        }

        // Calculate rotation

        float rot = rotation * turningSpeed * -1 * angularDrag * rb.mass;

        // Apply terrain traction

        rot  *= traction * traction;
        vert *= traction * traction;

        // Apply velocity

        rb.AddForce(rb.transform.up * vert
                    * speed
                    * rb.mass
                    * drag
                    );

        // Apply rotation
        rb.AddTorque(rot);

        // Set animated track speed

        foreach (Animator a in leftTrackAnims)
        {
            a.SetFloat(
                "Speed", (transform.InverseTransformDirection(rb.velocity).y + (rot / 15f) * rotationMultiplier) * animationMultiplier);
        }
        foreach (Animator a in rightTrackAnims)
        {
            a.SetFloat("Speed", (transform.InverseTransformDirection(rb.velocity).y - (rot / 15) * rotationMultiplier) * animationMultiplier);
        }

        // Set sound level

        if (engineSound != null)
        {
            set.SetVolume((float)engineStress);

            src.pitch = 0.25f + (float)(engineStress / 1.5) * pitcher;
        }
    }
コード例 #30
0
        void Update()
        {
            float throttle = Input.GetAxis("Horizontal");
            float pitch    = Input.GetAxis("Vertical");

            if (throttle > 0.0f && throttle > lastInputThrottleValue)
            {
                this.throttle += throttle;
                if (this.throttle > 1)
                {
                    this.throttle = 1;
                }
                ThrottleSlider.value = this.throttle;
            }
            else if (throttle < 0.0f && throttle < lastInputThrottleValue)
            {
                this.throttle -= throttle * -1;
                if (this.throttle < 0)
                {
                    this.throttle = 0;
                }
                ThrottleSlider.value = this.throttle;
            }
            lastInputThrottleValue = throttle;
            if (pitch > 0.0f && pitch > lastInputPitchValue)
            {
                this.Pitch += pitch;
                if (this.Pitch > 1)
                {
                    this.Pitch = 1;
                }
            }
            else if (pitch < 0.0f && pitch < lastInputPitchValue)
            {
                this.Pitch -= pitch * -1;
                if (this.Pitch < -1)
                {
                    this.Pitch = -1;
                }
            }
            lastInputPitchValue = pitch;
            if (Throttle < 0.25f) // going too slow, plane starts to drop
            {
                _rb.gravityScale = 1 * (0.25f - Throttle);
            }
            //todo if over 0.9, plane goes up
            else
            {
                _rb.gravityScale = 0;
            }

            /*else
             * {
             *  if (_rb.angularVelocity > 0.01f)
             *  {
             *      _rb.angularVelocity /= 2;
             *  }
             *  else
             *  {
             *      _rb.angularVelocity = 0;
             *  }
             *
             * }*/

            _rb.AddTorque(PitchTorque * Maneuverability, ForceMode2D.Force);
        }