Version: 6000.3
语言: 中文
3. 移动角色
5. 碰撞测试

4. 伸手棒测试

学习目标

对您的角色位置和行为执行断言。

锻炼

  1. 返回上一个MovementTest.cs文件。
  2. 写一个MainScene\_CharacterReachesWand测试是否使您的角色向右移动,并检查它是否到达魔杖位置。

提示

  • 在您的 场景场景包含游戏的环境和菜单。将每个唯一的场景文件视为一个独特的关卡。在每个场景中,你放置你的环境、障碍物和装饰品,基本上是将你的游戏设计和构建成碎片。更多信息
    请参阅术语表
    .你对测量变换对象的 X 位置感兴趣。
  • 魔杖位置 X 位置等于 21.080 的浮点。主角 X 位置是动态的,每当它移动时都会发生变化。
  • 考虑设置一个超时,如果未达到魔杖,则测试失败。

溶液

using System.Collections;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.SceneManagement;

public class MovementTest
{
    private Transform _characterTransform;
    private float _testTimeout = 25.0f;
    private float _wandLocation = 21.080f;

    [UnityTest]
    public IEnumerator MainScene_CharacterReachesWand()
    {
      SceneManager.LoadScene("Assets/Scenes/Main.unity", LoadSceneMode.Single);
      yield return waitForSceneLoad();

      var elapsedTime = 0.0f;
      yield return GoRight();
      while (GetCurrentCharacterPosition() <= _wandLocation)
      {
          yield return null;
          elapsedTime += Time.deltaTime;
          if (elapsedTime > _testTimeout)
          {
            Assert.Fail($"Character did not reach location position in {_testTimeout} seconds.");
          }
      }
    }

    private float GetCurrentCharacterPosition()
    {
      // Get Main character's Transform which is used to manipulate position.
      if (_characterTransform == null)
      {
          _characterTransform = GameObject.Find("Sara Variant").transform;
      }

      return _characterTransform.position.x;
    }

    private IEnumerator GoRight()
    {
      TestInputControl.MoveLeft = false;
      yield return null;
      TestInputControl.MoveRight = true;
    }

    private IEnumerator waitForSceneLoad()
    {
        while (SceneManager.GetActiveScene().buildIndex > 0)
        {
            yield return null;
        }
    }
}
3. 移动角色
5. 碰撞测试