繁体   English   中英

根据您在Unity中查看对象的时间重置计时器

[英]Reset a timer based on when you look at an object in Unity

我已经在Unity中设置了射线投射,该射线投射可根据对象的标记来检测何时查看该对象。 现在,我想做的是有一个定时事件,当我在一段时间内查看标记的对象时触发该事件,然后当我移开目光时希望计时器重置。

但是,要使它正常工作我确实遇到了麻烦。 有人可以看看我的代码并指出我在做什么错吗?

public float end_time = 10.0f;
public float start_time;

// Use this for initialization
void Start () 
{
    start_time = Time.deltaTime;
}

// Update is called once per frame
void Update () 
{

    EyeTarget();
}

void EyeTarget()
{
    RaycastHit hit;
    Vector3 fwd = transform.TransformDirection(Vector3.forward);
    if (Physics.Raycast(transform.position, fwd, out hit))
    {
     //  Debug.Log("ray hit (tag): " + hit.collider.gameObject.tag + " : ");
        if(hit.collider.gameObject.tag == "floor")
        {
            Debug.Log("Just hit the floor");

            start_time = Time.time - end_time;
            if(start_time <= 0)
            {
                Debug.Log("looked at floor for 10 seconds");
            }
        }

        if( hit.collider.gameObject.tag != "floor")
        {
            ResetTimer();

        }
    }
    Debug.DrawRay(transform.position, fwd, Color.green);
}

void ResetTimer()
{
    start_time = Time.time;
    Debug.Log("resetting timer");
}

在我使用略有不同的方法的情况下,请尝试以下方法:

    public float end_time = 10.0f;
    public float start_time;
    private float running_time;

    // Use this for initialization
    void Start () 
    {
        start_time = Time.deltaTime;
        running_time = 0f;
    }

    // Update is called once per frame
    void Update () 
    {

        EyeTarget();
    }

    void EyeTarget()
    {
        RaycastHit hit;
        Vector3 fwd = transform.TransformDirection(Vector3.forward);
        if (Physics.Raycast(transform.position, fwd, out hit))
        {
         //  Debug.Log("ray hit (tag): " + hit.collider.gameObject.tag + " : ");
            if(hit.collider.gameObject.tag == "floor")
            {
                Debug.Log("Just hit the floor");

                start_time = Time.time - end_time;
                running_time += Time.deltaTime
                //if(start_time <= 0)
                if ( running_time >= end_time )
                {
                    Debug.Log("looked at floor for 10 seconds");
                }
            }

            if( hit.collider.gameObject.tag != "floor")
            {
                ResetTimer();

            }
        }
        Debug.DrawRay(transform.position, fwd, Color.green);
    }

    void ResetTimer()
    {
        start_time = Time.time;
        running_time = 0f;
        Debug.Log("resetting timer");
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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