简体   繁体   中英

Stopwatch in c# (unity)

i'm making a door (similiar to the Doom 64's ones) and i have this code:

public class aperturaPorta : MonoBehaviour
{
public Transform playerCheck;
public Vector3 halfSize = new Vector3 (3f, 3f, 0.5f);
public LayerMask playerLayer;
bool playerEntering = false;

public BoxCollider collider;
public MeshRenderer renderer;

bool aprendo = false;
bool chiudendo = false;

public float openSpeed;
int counter = 1;
public int tick = 99;

// Update is called once per frame
void Update()
{
    playerEntering = Physics.CheckBox(playerCheck.position, halfSize, Quaternion.identity, playerLayer, QueryTriggerInteraction.UseGlobal);

    if (playerEntering && Input.GetButtonDown("e")) {
        aprendo = true;
        chiudendo = false;
    } 

    if (counter == 100) {
        chiudendo = true;
    }

    if (aprendo) {
        transform.position += new Vector3 (0f, openSpeed, 0f);
        counter += 1;
        if (counter > tick) {
            aprendo = false;
            chiudendo = true;
        }
    }

    if (chiudendo) {
        transform.position -= new Vector3 (0f, openSpeed, 0f);
        counter -= 1;
        if (counter < 1) {
            chiudendo = false;
        }
    }
}
}

This work but the door start closing when it finishes openening but it's too fast so i want to implement a two or three seconds stopwatch so that when it finishes the door start closing, how can i do it? thank you

ps: excuse me but i'm a newbie in unity

If I understand correctly you want a simple delay when the door is open before it closes? Keeping the same code structure you can add an other counter for that.

public float openSpeed;
int counter = 1;
public int tick = 99;
public int delayTicks = 100;
private int delayCounter = 0;

// Update is called once per frame
void Update()
{
    playerEntering = Physics.CheckBox(playerCheck.position, halfSize, Quaternion.identity, playerLayer, QueryTriggerInteraction.UseGlobal);

    if (playerEntering && Input.GetKeyDown(KeyCode.P))
    {
        aprendo = true;
        chiudendo = false;
    }

    if (counter == 100)
    {
        chiudendo = true;
    }

    if (aprendo)
    {
        transform.position += new Vector3(0f, openSpeed, 0f);
        counter += 1;
        if (counter > tick)
        {
            delayCounter = delayTicks;
            aprendo = false;
        }
    }

    if (delayCounter > 0) 
    {
        delayCounter--;
        if (delayCounter <= 0)
        {
            chiudendo = true;
        }
    }
    else if (chiudendo)
    {
        transform.position -= new Vector3(0f, openSpeed, 0f);
        counter -= 1;
        if (counter < 1)
        {
            chiudendo = false;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM