- Home /
Question by
ToastandBananas · Jun 29, 2018 at 09:24 PM ·
unity 52danimatorcollider2d
All of my doors are opening at the same time. Why?
So I just wrote up a simple door open and close script. It works, except for the fact that all of my doors open/close at the same time. How do I make it so that only the door that I'm interacting with opens/closes? I'm using a BoxCollider2D as a trigger to determine if the player is within range of the door and then you press E to open or close it.
using UnityEngine;
public class Door : MonoBehaviour {
Player player;
Transform door;
BoxCollider2D playerCollider;
BoxCollider2D doorTriggerCollider;
BoxCollider2D doorCollider;
Animator doorAnim;
public enum DoorState
{
Closed = 0,
OpenLeft = 1,
OpenRight = 2
}
DoorState startDoorState;
DoorState currentDoorState;
// Use this for initialization
void Start () {
player = Player.instance;
door = transform.parent;
playerCollider = player.GetComponent<BoxCollider2D>();
doorTriggerCollider = GetComponent<BoxCollider2D>();
doorCollider = door.GetComponent<BoxCollider2D>();
startDoorState = DoorState.Closed;
currentDoorState = startDoorState;
doorAnim = door.GetComponent<Animator>();
Physics2D.IgnoreCollision(playerCollider, doorTriggerCollider);
}
// Update is called once per frame
void Update () {
if (currentDoorState == DoorState.Closed)
{
doorAnim.SetInteger("doorState", 0);
doorCollider.enabled = true;
}
else if (currentDoorState == DoorState.OpenLeft)
{
doorAnim.SetInteger("doorState", 1);
doorCollider.enabled = false;
}
else if (currentDoorState == DoorState.OpenRight)
{
doorAnim.SetInteger("doorState", 2);
doorCollider.enabled = false;
}
}
void OnTriggerStay2D(Collider2D collision)
{
if (collision = playerCollider)
{
if (currentDoorState == DoorState.Closed)
{
if (door.position.x > player.transform.position.x)
{
if (Input.GetKeyDown(KeyCode.E))
{
currentDoorState = DoorState.OpenRight;
}
}
else if (door.position.x < player.transform.position.x)
{
if (Input.GetKeyDown(KeyCode.E))
{
currentDoorState = DoorState.OpenLeft;
}
}
}
else
{
if (Input.GetKeyDown(KeyCode.E))
{
currentDoorState = DoorState.Closed;
}
}
}
}
}
Comment
Your answer
Follow this Question
Related Questions
2D Animation does not start 1 Answer
Dynamic way to adjust animated sprite length 0 Answers
Animation is not playing all frames 0 Answers
Trying to reset lvl on collsion 1 Answer
Force PolygonCollider2D into a Square or Autofit BoxCollider2D 0 Answers