Search Unity

Gliding of Hero

Discussion in '2D' started by Abhi199, Jul 16, 2018.

  1. Abhi199

    Abhi199

    Joined:
    Jul 16, 2018
    Posts:
    5
    I want to make my hero glide in air when the player presses particular key. How can I do that?
     
  2. turp182

    turp182

    Joined:
    May 3, 2018
    Posts:
    52
    This is not tested, but it should be close.

    Use Debug.log to track things in the Console. This will get it to go up and stop at a specified height. Add a time variable and track Time.unscaledTime or however you are doing time to determine when to apply a negative force, basically reversing the two situations below.

    Add the compiling script to the Hero. Set the height in the script component UI.

    class HeroGlide()
    {

    private RigidBody2D body;
    private SpriteRenderer renderer;
    public float height;

    public float startingHeight;

    private void Start()
    {
    body = GetComponent<RigidBody2D>():
    SpriteRenderer = GetComponent<SpriteRenderer>();

    startingHeight = renderer.transform.position.y;
    }

    private void Update/FixedUpdate()
    {
    if (renderer.transform.position.y < height + minHeight)
    {
    //apply some force upward
    body.AddForce(new Vector2(0, 3); // 3 is the upward force amount, play with different values
    }
    else if (renderer.transform.position.y > startingHeight + height) // reached target height
    {
    // this code block can be used in the other if clauses, it stops the body on the y axis
    Vector2 vector = body.velocity;
    vector.y = 0f;
    body.velocity = vector;
    }

    }

    }