Advertisement
MariuszPoz

Unity - Interacting with objects - opening the door

Jan 3rd, 2025 (edited)
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.73 KB | Source Code | 0 0
  1. // THIS SCRIPT IS EXPLAINED HERE:
  2. // https://unity-is-easy.blogspot.com/2025/01/interacting-with-objects-in-unity.html
  3. // VISIT MY PAGE TO LEARN SOME UNITY :)
  4.  
  5. using UnityEngine;
  6.  
  7. public class DoorController : MonoBehaviour
  8. {
  9.     public GameObject door;
  10.     public float openRot = 115; // angle when door is open
  11.     public float closeRot = 0; // angle when door is closed
  12.     public float speed = 2; // speed of opening/closing door
  13.     public bool opening; // true or false if open
  14.  
  15.     public Transform player; // Reference to the player (drag the player object here in the Inspector)
  16.     public float activationDistance = 3f; // Distance threshold for interaction
  17.  
  18.  
  19.     // Update is called once per frame
  20.     void Update()
  21.     {
  22.         // Calculate distance between player and door
  23.         float distance = Vector3.Distance(player.position, transform.position);
  24.        
  25.         Vector3 currentRot = door.transform.localEulerAngles;
  26.         if (opening)
  27.         {
  28.             if (currentRot.y < openRot)
  29.             {
  30.                 door.transform.localEulerAngles = Vector3.Lerp(currentRot, new Vector3(currentRot.x, openRot, currentRot.z), speed * Time.deltaTime);
  31.             }
  32.         }
  33.         else
  34.         {
  35.             if (currentRot.y > closeRot)
  36.             {
  37.                 door.transform.localEulerAngles = Vector3.Lerp(currentRot, new Vector3(currentRot.x, closeRot, currentRot.z), speed * Time.deltaTime);
  38.             }
  39.         }
  40.  
  41.         // Check if player is close enough and presses the 'F' key
  42.         if (distance <= activationDistance && Input.GetKeyDown(KeyCode.F))
  43.         {
  44.             ToggleDoor();
  45.         }
  46.  
  47.  
  48.     }
  49.  
  50.     public void ToggleDoor()
  51.     {
  52.         opening = !opening;
  53.     }
  54. }
  55.  
Tags: C# Unity
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement