Search Unity

Door Problem

Discussion in 'Scripting' started by KingLlama, Sep 3, 2015.

  1. KingLlama

    KingLlama

    Joined:
    Jul 18, 2015
    Posts:
    199
    So the box collider moves but the mesh render doesn't move. What am I doing wrong?
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class MoveDoors : MonoBehaviour {
    5.     public float rotateXAmount=0f;
    6.     public float rotateYAmount=0f;
    7.     public float rotateZAmount=0f;
    8.     bool rotated=false;
    9.     GameObject me=null;
    10.  
    11.     void Start(){
    12.         me=this.gameObject;
    13.     }
    14.  
    15.     public void DoorMove(){
    16.         if(rotated==false){
    17.             me.transform.Rotate(rotateXAmount,rotateYAmount,rotateZAmount);
    18.             rotated=true;
    19.         }
    20.         else{
    21.             rotated=false;
    22.             me.transform.Rotate(-rotateXAmount,-rotateYAmount,-rotateZAmount);
    23.         }
    24.     }
    25. }
     
  2. ArachnidAnimal

    ArachnidAnimal

    Joined:
    Mar 3, 2015
    Posts:
    1,813
    Make sure the door is not marked batching static
     
    KingLlama likes this.
  3. KingLlama

    KingLlama

    Joined:
    Jul 18, 2015
    Posts:
    199
    Now it works but i'm running into a new problem because it doesn't have a correct pivot. It's a middled pivot even if I add a parent object to it. It doesn't work at all then.
     
  4. ArachnidAnimal

    ArachnidAnimal

    Joined:
    Mar 3, 2015
    Posts:
    1,813
    There are numerous ways to do this. The way I do door is to position the door properly in the 3d tool such that the hinges are at the origin. For example:

    door2.png

    The pivot point is at the hinges.

    The the door can be rotated using:
    Code (csharp):
    1.  
    2. door.transform.eulerAngles=new Vector3(
    3. door.transform.eulerAngles.x,
    4. someNewYAngle,
    5. door.transform.eulerAngles.z);
    6.  
    All it does it rotates it around the Y-axis (Unity-up) axis.

    If it wasn't centered, you could probably rotate it around a specific point, but you would need to know the world point which might not be easy to determine.
    You could put a Unity cube at the hinge and then tell the door to rotate around the position of the dummy cube.

    Code (csharp):
    1.  
    2. door.transform.RotateAround(dummyCube.transform.position, Vector3.up, speed * Time.deltaTime);
    3.  
     
    KingLlama likes this.
  5. KingLlama

    KingLlama

    Joined:
    Jul 18, 2015
    Posts:
    199
    Thank you this is definitely something I have to do. Great information!!!
     
    ArachnidAnimal likes this.