Mobile Game Tutorial part 03 – launch platform.

Hi, part 3 of mobile game turorial series is now available.

CODE:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class LaunchPlatform : MonoBehaviour
{
    public GameObject powerBarGO;
    public Image PowerBarMask;
    public float barChangeSpeed = 1;
    float maxPowerBarValue = 1;
    float currentPowerBarValue;
    bool powerIsIncreasing;
    bool PowerBarON;

    public float launchForceMultiplier;
    Rigidbody2D rb2d;
    // Start is called before the first frame update
    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
        currentPowerBarValue = 0;
        powerIsIncreasing = true;
        PowerBarON = true;
        StartCoroutine(UpdatePowerBar());
    }

    private void FixedUpdate()
    {
        CheckPlatformPos();
    }

    IEnumerator UpdatePowerBar()
    {
        while (PowerBarON)
        {
            if (!powerIsIncreasing)
            {
                currentPowerBarValue -= barChangeSpeed;
                if (currentPowerBarValue <= 0)
                {
                    powerIsIncreasing = true;
                }
            }
            if (powerIsIncreasing)
            {
                currentPowerBarValue += barChangeSpeed;
                if (currentPowerBarValue >= maxPowerBarValue)
                {
                    powerIsIncreasing = false;
                }
            }

            float fill = currentPowerBarValue / maxPowerBarValue;
            PowerBarMask.fillAmount = fill;
            yield return new WaitForSeconds(0.02f);

            if (Input.touchCount > 0)
            {
                PowerBarON = false;
                LaunchRocket();
                StartCoroutine(TurnOffPowerBar());

            }
        }
        yield return null;
    }
    IEnumerator TurnOffPowerBar()
    {
        yield return new WaitForSeconds(0.5f);
        powerBarGO.SetActive(false);
    }

    public void CheckPlatformPos()
    {
        if (this.transform.position.y >= -3.0f)
        {
            rb2d.velocity = new Vector2(0, 0);
            rb2d.bodyType = RigidbodyType2D.Static;
        }
        if(this.transform.position.y < -3.5f)
        {
            rb2d.bodyType = RigidbodyType2D.Static;
            this.transform.position = new Vector2(0, -3.5f);
        }
    }
    public void LaunchRocket()
    {
        rb2d.bodyType = RigidbodyType2D.Dynamic;
        float _launchForce = currentPowerBarValue * launchForceMultiplier;
        Vector2 _launchForceVector = new Vector2(0, _launchForce);
        rb2d.AddForce(_launchForceVector, ForceMode2D.Impulse);

        Debug.Log("RocketLaunched");

    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *