- Home /
How to close an open door?
I have a door in a top down 2d game that swings on a Hinge Joint 2D. At the start of the game the door is set to kinematic and when the player is nearby and presses E it's set to dynamic and swings freely.
I'd like the door to automatically close again when it swings back to its original position. I've got the below code, but now the doors don't open at all. Is there a better way to accomplish this? I've confirmed isOpen is set to true only when the door is open.
void Update () {
//check if locked
//open door if E is pressed near it
if(Input.GetKeyDown(KeyCode.E) && isOpen == false && isLocked == false){
openDoor();
}else if(Input.GetKeyDown(KeyCode.E) && isLocked == true){
lockChecker();
}
//if door swings back, close
if(transform.position == startingPosition.transform.position && isOpen == true && lastOpenTime > .5f){
closeDoor();
}
}
void closeDoor(){
rb.bodyType = RigidbodyType2D.Kinematic;
doorAudio.PlayOneShot(doorLock);
isOpen = false;
isLocked = false;
lastOpenTime = 0.0f;
}
Debug the code, and the inspector while running, check why is not opening. You get it at first so, you should changed something. IS the doorkinematinc all time? maybe you are calling the Close function all time, or at same time players try to open... somethig like this.
Answer by JPhilipp · Feb 15, 2020 at 11:19 AM
Here's a bit of refactor to better express logic and intent -- note how you can write "!isOpen" instead of "isOpen == false", and note how function names are usually starting with a capital letter. Also, note how you need to assign a Time.time to lastOpenTime:
void Update ()
{
if (Input.GetKeyDown(KeyCode.E) && !isOpen)
{
if (isLocked)
{
LockChecker();
}
else
{
OpenDoor();
}
}
if (isOpen && Time.time - lastOpenTime >= 0.5f)
{
CloseDoor();
}
}
void OpenDoor()
{
isOpen = true;
lastOpenTime = Time.time;
}
void CloseDoor()
{
isOpen = false;
rb.bodyType = RigidbodyType2D.Kinematic;
doorAudio.PlayOneShot(doorLock);
}
I left out your transform.position for now as I wasn't sure what you intended it to do, so feel free to bring it back. Good luck!
Your answer
Follow this Question
Related Questions
Avoiding 2D top-down diagonal movement 2 Answers
Rigidbody2D drifitng after collision 2 Answers
Prevent gameobjects from overlapping - 2D 0 Answers
How to freeze all enemy objects at once 1 Answer
Unity 2d mobile movement 0 Answers