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 to make an object turn then stop at a certain rotation.y when using physics?

Discussion in 'Scripting' started by Pur3, Feb 12, 2016.

  1. Pur3

    Pur3

    Joined:
    Jun 14, 2015
    Posts:
    4
    So I am not really sure how to go about this at all. I am trying to have an object spin when the player walks into the object (lets call it Turnstile). When the player walks to the Turnstile, it spins using a rigidbody. When this Turnstile spins to 150 (on the y axis of rotation) it should lock and not move anymore. I have been looking around the internet and I see people having code dealing with Time.deltaTime and having their objects always spinning but mine is being pushed by the player. I am not really sure how to go about this at all and was wondering if anyone had ideas. Thank you in advance!

    Important note: I have the X Y Z of the position frozen and the X Z of rotation frozen so this object is only meant to turn on the Y rotation axis
     
  2. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    Sounds like you need to use a lerp not physics. I assume you're doing an on trigger enter.

    Something like this might work. I'm sure I'm missing some peace of the code. but it's close. I sometime have to use eulerAngles
    transform.rotation.eulerAngles

    Code (CSharp):
    1.  
    2. public class MyClass : MonoBehaviour {
    3.  
    4. public Vector3 startMarker;
    5. public Vector3 endMarker;
    6. public float speed = 1.0F;
    7. private float startTime;
    8. private float journeyLength;
    9.  
    10. void OnTriggerEnter()
    11. {
    12.  
    13. startMarker = transform.rotation;
    14.  
    15. endMarker = new Vector3(0,150,0);
    16.  
    17. startTime = Time.time;
    18.  
    19. journeyLength = Vector3.Distance(startMarker, endMarker);
    20.  
    21. float distCovered = (Time.time - startTime) * speed;
    22.  
    23. float fracJourney = distCovered / journeyLength;
    24.  
    25. transform.rotation = Vector3.Lerp(startMarker, endMarker, fracJourney);
    26.  
    27. }
    28.  
    29. }
     
  3. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    other wise you could build an if statement of function to check what the current y value is and then disable the rigidbody.

    "not real code"
    if(door.rotaion.y == 150)
    {
    rigidbody.velocity = 0;
    rigidbody.enable = false;
    }