我正在尝试创建类似z-type的文字游戏。游戏开始后,屏幕上会显示一些单词。当用户键入字母,并且如果该字母与显示的任何单词的第一个字母匹配时,都会在该单词上添加activeWord标记。我还创建了一个激光脚本,用于检查标签是否处于活动状态,以及何时发生,它会发射激光。

现在发生的情况是,激光仅发射一次,即当第一个字母匹配时,而键入其余单词时不发射激光。

这是激光脚本:

using UnityEngine;
using UnityEngine.UI;

public class Laser : MonoBehaviour {
    public float speed = 10.0f;
    private Vector3 laserTarget;

    private void Update () {
        GameObject activeWord = GameObject.FindGameObjectWithTag("activeWord");

        if (activeWord && activeWord.GetComponent<Text>().text.Length > 0) {
            laserTarget = activeWord.transform.position; // find position of word
            transform.Translate(laserTarget * speed * Time.deltaTime); // shoot the laser
        }
    }
}


我还添加了在display / UI字段中使用的代码。

public void RemoveLetter() {
/* remove the first letter if its correct and so
on for the remaining letters. change the color of the word to red and add
the "activeddWord" tag.*/
    text.text = text.text.Remove(0, 1);
    text.color = Color.red;
    text.gameObject.tag = "activeWord";
}

public void RemoveWord() { // destroy the word once all the letters match
    Destroy(gameObject);
}


有人可以看一下代码,然后告诉我我在哪里出错。

最佳答案

我认为如果到达目标,您必须重置激光的位置:

public float speed = 10.0f;
private Vector3 laserTarget;
private Vector3 laserOrigin;

private void Start () {
    // save laser's origin position
    laserOrigin = transform.position;
}


private void Update () {
    GameObject activeWord = GameObject.FindGameObjectWithTag("activeWord");

    if (activeWord && activeWord.GetComponent<Text>().text.Length > 0)
    {
        laserTarget = activeWord.transform.position; // find position of word
        transform.Translate(laserTarget * speed * Time.deltaTime); // shoot the laser

        float distance = Vector3.Distance(laserTarget , transform.position);
        if(distance < 0.05f){ // I don't know your scaling, perhaps change the limit here!
            transform.position = laserOrigin;
        }
    }
}

关于c# - 在Unity中连续发射激光,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50753973/

10-10 10:00