Unity如何暂时忽略更新功能[C#]

时间:2016-08-10 15:12:57

标签: c# variables unity3d unity5 raycasting

我将尝试以最简单的方式解释这一点。我正在为一名敌方玩家制作一些AI。我希望如果它的射线投射击中了玩家,AI会向后移动,但是我遇到了严重的问题。 [我将在下面解释代码]

代码;

using UnityEngine;
using System.Collections;

public class NewEnemyAI : MonoBehaviour 
{
    public GameObject enemy;
    public Transform target;
    public float movementSpeed = 2f;

    private CharacterController enemyCharacterController;
    private bool enemyHit;
    private Vector3 startPos;
    private Vector3 endPos;
    private float distance = 7f;
    private float lerpTime = 0.3f;
    private float currentLerpTime = 0f;
    private bool avoid;
    private bool updateOn = true;
    private bool hitPlayer = false;


    // Use this for initialization
    void Start () 
    {
        avoid = false;
    }

    // Update is called once per frame
    void Update () 
    {
        //raycasting
        if (Physics.Raycast(transform.position, transform.forward, 2))
        {
            startPos = enemy.transform.position;
            endPos = enemy.transform.position + Vector3.back * distance;
            avoid = true;
        }
        else
        {
            avoid = false;
        }

        if (avoid == true)
        {
            currentLerpTime += Time.deltaTime;
            if (currentLerpTime >= lerpTime)
            {
                currentLerpTime = lerpTime;
            }

            float perc = currentLerpTime/lerpTime;
            enemy.transform.position = Vector3.Lerp(startPos, endPos, perc);

            avoid = false;
        }

        if (avoid == false)
        {
            currentLerpTime = 0;
            transform.LookAt(target);
            transform.Translate(Vector3.forward * Time.deltaTime * movementSpeed);
        }
    }
}

当敌人的光线投射击中玩家时,我将布尔设置为真,当这是真的时,它会让玩家向后移动。然而,因为玩家正在向后移动,光线投射不会再击中玩家,然后整个过程再次开始,敌人只是橡皮筋,因为它从代码跳到代码。有没有办法让代码忽略光线投射if语句并永久地将avoid bool设置为true,直到另有说明为止。谢谢! [我对C#比较新,所以请不要过多批评我的代码]。

1 个答案:

答案 0 :(得分:2)

轻松修复:向if语句添加计时器:

if (Physics.Raycast(transform.position, transform.forward, 2) && timePassed(timestamp))

然后你可以根据这个例子实现timePassed函数:

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public GameObject projectile;
    public float fireRate = 0.5F;
    private float nextFire = 0.0F;
    void Update() {
        if (Input.GetButton("Fire1") && Time.time > nextFire) {
            nextFire = Time.time + fireRate;
            GameObject clone = Instantiate(projectile, transform.position, transform.rotation) as GameObject;
        }
    }
}

来源:https://docs.unity3d.com/ScriptReference/Time-time.html

但是,您应该考虑重构您的代码,牢记有针对性的编程规则 - 从良好的资源中学习可以在一天结束时带来很多,然后在床设计代码中犯错并尝试修补它们。

我建议从桌面到桌面阅读一些优秀的C#教程,并编写游戏来练习你学到的东西。