Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How do I program C# altitude/altimeter in a 2D platformer?

Discussion in 'Scripting' started by Samuel_Develops, Oct 21, 2021.

  1. Samuel_Develops

    Samuel_Develops

    Joined:
    Oct 21, 2021
    Posts:
    5
    Hello,

    So I'm part of making a basic 2D platformer where you advance upwards & I need there to be a HUD that shows player altitude, perhaps in ft & km as a sign of player progress.

    Idk if I'm programming an altimeter or what, but since the game is 2D, there's really no need pointing anything as rotation pointers.

    Just 2D values going up. So I guess there needs to be raycast pointing on Y axis at the very least. And some way for game to set height units and add them as the player goes up.

    Thanks for anyone who replies!
     
    Last edited: Oct 21, 2021
  2. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
    It's worth noting what altitude actually is in order to understand the maths behind it but you're already halfway there knowing that you can use a raycast. In this case you would measure with a raycast the distance from the player to the ground and that will give you the correct end result but unity has a feature for this called vector3.distance as well.

    https://www.dictionary.com/browse/altitude

    https://docs.unity3d.com/ScriptReference/Vector3.Distance.html

    https://docs.unity3d.com/ScriptReference/RaycastHit-distance.html
     
    Joe-Censored and GroZZleR like this.
  3. Samuel_Develops

    Samuel_Develops

    Joined:
    Oct 21, 2021
    Posts:
    5
  4. davidnibi

    davidnibi

    Joined:
    Dec 19, 2012
    Posts:
    426
    Above states that altitude is distance above sea level - did you want it above ground level (unfixed) or a fixed level (ie the sea). You could simply refer to your object's Y coordinate in 2D?
     
    Joe-Censored and Lethn like this.
  5. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
    Yes, I was just looking at it for general reference, in the OP's case it doesn't necessarily need to be explicit unless they want to get really anal about the maths. When it comes to games and the like of course if you're not going to be realistic about it sea level could be entirely made up anyway.
     
    Last edited: Oct 24, 2021
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,522
    What you describe is just a vertical distance measure, not really an altimeter (or radar altimeter) in the general sense.

    All you need is to copy the
    transform.position.y
    value out and use that (perhaps after subtracting the initial .y value you start at, if it is not zero) for your score.

    You do not care about raycast if you don't care how far a varying ground is below you.