有没有更好的方法让对象自动移动

时间:2017-08-04 18:37:27

标签: c# user-interface unity3d

我正在制作物体(在这种情况下是汽车)根据时间点自动移动:

    public Image car1_right;
    public int k;
    public float i;
    public float j;

    void Start()
    {
        k = 1;
        i = 0f;
        j = 0f;
        car1_right.enabled = false;
    }
    void Update()
    {
        if (TimeManager.gametimeDecimal == 9.0m && k == 1)
        {
            car1_right.enabled = true;
            InvokeRepeating("car_move_1", 0f, 0.05f);
            k = 2;
        }
        if (TimeManager.gametimeDecimal == 23.0m && k == 2)
        {
            k = 1;
            i = 0f;
            j = 0f;
        }
    }
    void car_move_1()
    {
        car1_right.transform.localPosition = new Vector3(-35.0f + i, 531f - j, 0);
        i += 1.8f;
        j += 0.85f;
    }

问题是,要添加更多2辆汽车,我必须为每个汽车再创建3个变量(这将是6个)并使代码重复三次。

你知道更好的方法吗?

1 个答案:

答案 0 :(得分:1)

window.addEventListener("load", () => {

  const audio = document.createElement("audio");

  audio.controls = "controls";

  document.body.appendChild(audio);

  audio.addEventListener("canplay", e => {
    audio.play();
  });

  const words = ["hello", "world"];

  const mediaSource = new MediaSource();

  const mimeCodec = "audio/mpeg";

  const mediaType = ".mp3";

  const url = "https://ssl.gstatic.com/dictionary/static/sounds/de/0/";

  Promise.all(
      words.map(word =>
        fetch(`https://query.yahooapis.com/v1/public/yql?q=select * from data.uri where url="${url}${word}${mediaType}"&format=json&callback=`)
        .then(response => response.json())
        .then(({
            query: {
              results: {
                url
              }
            }
          }) =>
          fetch(url).then(response => response.body.getReader())
          .then(readers => readers)
        )
      )
    )
    .then(readers => {

      audio.src = URL.createObjectURL(mediaSource);
      mediaSource.addEventListener("sourceopen", sourceOpen);

      async function sourceOpen() {
        var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
        // set `sourceBuffer` `.mode` to `"sequence"`
        sourceBuffer.mode = "segments";

        const processStream = ({
          done,
          value
        }) => {
          if (done) {
            return;
          }
          // append chunk of stream to `sourceBuffer`
          sourceBuffer.appendBuffer(value);
        }
        // at `sourceBuffer` `updateend` call `reader.read()`,
        // to read next chunk of stream, append chunk to 
        // `sourceBuffer`
        for (let [index, reader] of Object.entries(readers)) {
          sourceBuffer.addEventListener("updateend", function() {
            reader.read().then(processStream);
          });

          let stream = await reader.read().then(processStream)
            .then(() => reader.closed)
            .then(() => "done reading stream " + index);

          console.log(stream);
        }

      }
    })
}) 

它可能看起来像这样。您将决定实施所需的逻辑。