Advertisement
vexe

Smooth door open C#

Dec 25th, 2013
389
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.70 KB | None | 0 0
  1. using System.Collections;
  2. using UnityEngine;
  3.  
  4. public class Door : MonoBehaviour
  5. {
  6.     //Make an empty game object and call it "Door"
  7.     //Rename your 3D door model to "Body"
  8.     //Parent a "Body" object to "Door"
  9.     //Make sure thet a "Door" object is in left down corner of "Body" object. The place where a Door Hinge need be
  10.     //Add a box collider to "Door" object and make it much bigger then the "Body" model, mark it trigger
  11.     //Assign this script to a "Door" game object that have box collider with trigger enabled
  12.     //Press "f" to open the door and "g" to close the door
  13.     //Make sure the main character is tagged "player"
  14.  
  15.     public float smooth = 2.0f;
  16.     public float openAngle = 90.0f;
  17.  
  18.     private bool open;
  19.     private bool inSight;
  20.     private Vector3 defaultRot;
  21.     private Vector3 openRot;
  22.     private Transform mTransform;
  23.     private Transform cachedTransform { get { if (!mTransform) mTransform = transform; return mTransform; } }
  24.  
  25.     void OnEnable()
  26.     {
  27.         defaultRot = cachedTransform.eulerAngles;
  28.         openRot = new Vector3(defaultRot.x, defaultRot.y + openAngle, defaultRot.z);
  29.     }
  30.  
  31.     void Update()
  32.     {
  33.         if (Input.GetKeyDown(KeyCode.E) && inSight) {
  34.             open = !open;
  35.         }
  36.  
  37.         Vector3 target = open ? openRot : defaultRot;
  38.         cachedTransform.eulerAngles = Vector3.Slerp(cachedTransform.eulerAngles, target, Time.deltaTime * smooth);
  39.     }
  40.  
  41.     void OnGUI()
  42.     {
  43.         if (inSight) {
  44.             GUI.Label(new Rect(Screen.width / 2 - 75, Screen.height - 100, 150, 30), "Press 'F' to open the door");
  45.         }
  46.     }
  47.  
  48.     void OnTriggerEnter(Collider other)
  49.     {
  50.         if (other.gameObject.tag == "Player") {
  51.             inSight = true;
  52.         }
  53.     }
  54.     void OnTriggerExit(Collider other)
  55.     {
  56.         if (other.gameObject.tag == "Player") {
  57.             inSight = false;
  58.         }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement