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

Detecting object rotation

Discussion in 'Scripting' started by ammenter, May 21, 2019.

  1. ammenter

    ammenter

    Joined:
    May 16, 2019
    Posts:
    10
    I need to check for object rotation to tell if an object has fallen over in a 3d game but I can't figure how transform. commands work or even if it's done with those. How could this be done?
    (unity 2018.2.21)
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,773
    The easiest way to do this is to use transform.up, which will give you the direction vector of the object's "up" axis. You can compare transform.up.y to a number. If it's 0, it's sideways; if it's 1, it's right side up; if it's -1, it's upside down.
     
  3. csofranz

    csofranz

    Joined:
    Apr 29, 2017
    Posts:
    1,556
    First, you should find a definition of what constitutes as 'fallen over'. A useful definition might be that the object's 'up' vector deviates more than 45 degrees from a reference up vector (e.g. the floor).

    If you can do that, the rest is simple:

    Code (CSharp):
    1. Vector3 refUp = referenceObject.transform.up;
    2. Vector3 playerUp = player.transform.up;
    3.  
    4. if (Vector3.Angle(refUp, playerUp) > 45f) {
    5.     // player has fallen over
    6. }
     
  4. ammenter

    ammenter

    Joined:
    May 16, 2019
    Posts:
    10
    Is it possible to use: {if (Transform.up.y > 0.4) {
    Debug.Log("fallen");
    }
    }
    ?
     
  5. csofranz

    csofranz

    Joined:
    Apr 29, 2017
    Posts:
    1,556
    It's certainly possible. However, if you do that, you should know what this means, and what preconditions this requires: mainly: that the object you are testing against is *always* on a perfectly level surface. It won't work correctly when the objct sits on a slanted surface (more precisely a surface with an inclination of d degrees where sin(d) < 0.4)
     
  6. ammenter

    ammenter

    Joined:
    May 16, 2019
    Posts:
    10
    I'm going, to be honest, I don't Understand how this works and how I would need to edit it
     
  7. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,773
    That's close, though that would actually only active when it hasn't fallen. Lower values = the top of the object is lower.

    Try putting Debug.Log("up.y is "+transform.up.y); in your Update, and just watch the values it has as your object is in various positions. That should help you determine what value you need to check for.
     
  8. ammenter

    ammenter

    Joined:
    May 16, 2019
    Posts:
    10
    Yeah accidentally had It the wrong way around, I tried it but I need to reference the Transform.up and I'm not sure how to do it.
     
    Last edited: May 21, 2019