这是我脚本的一部分。 GameObjects在我期望的时候不会产生。我试图改变与延迟值相关的时间尺度(即,时间尺度= 1& baseDelay = .1f到时间尺度= 10& baseDelay = 1)。这有点像魅力,我真的不知道为什么。我的代码有问题吗? FixedUpdate和小浮点数存在统一问题吗?
图片:
using System; using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameController : MonoBehaviour {
internal int xCount = 5; //bricks in x per line
internal float spacing = .5f; //space between bricks and margin to edges
internal float baseDelay = .1f; //time that needs to pass until the next movement internal
float brickMovementPerStep = .05f; //movement distance per step
int currentLineNumber = 0; //index for current line
void FixedUpdate()
{
//accurate value of space which needs to pass
float dist = ((screenSize.x - (2 * spacing + ((xCount - 1) * spacing))) / xCount) * .667f + spacing;
float stepsPerSecond = 1 / baseDelay; //how many steps are there per second?
float movementPerSecond = stepsPerSecond * brickMovementPerStep; //how far will a line have moved?
float requiredTime = dist / movementPerSecond; //how long will a line need to travel until the next one can be spawned?
timeSinceLastSpawn += Time.deltaTime;
if(timeSinceLastSpawn >= requiredTime)
{
timeSinceLastSpawn = 0; //reset time
currentLineNumber++;
SpawnAndStartLevel(); //this instantiates and moves the line, it is moved continously
}
}
答案 0 :(得分:1)
Time.deltaTime
将用于更新每一帧的函数。 FixedUpdate()
不会每帧运行。 FixedUpdate()
用于物理 - 因为你没有做任何物理,你应该将它重命名为Update()
。我敢打赌,这将解决你的时间错误。 Read More
答案 1 :(得分:0)
当然可能发生舍入错误。我建议使用带有yield return WaitForSeconds(float)
的Coroutine,因为你似乎在固定的时间间隔内做了什么。
internal int xCount = 5; //bricks in x per line
internal float spacing = .5f; //space between bricks and margin to edges
internal float baseDelay = .1f; //time that needs to pass until the next movement internal
float brickMovementPerStep = .05f; //movement distance per step
int currentLineNumber = 0; //index for current line
bool run = true;
bool reset = false;
void Start() {
StartCoroutine(LineRoutine(baseDelay));
}
public IEnumerator LineRoutine(float delay) {
while (run){
float dist = ((screenSize.x - (2 * spacing + ((xCount - 1) * spacing))) / xCount) * .667f + spacing;
float stepsPerSecond = 1 / delay; //how many steps are there per second?
float movementPerSecond = stepsPerSecond * brickMovementPerStep; //how far will a line have moved?
float requiredTime = dist / movementPerSecond; //how long will a line need to travel until the next one can be spawned?
while (!reset) {
// stuff to happen every [requredTime] seconds
yield return new WaitForSeconds(requiredTime);
currentLineNumber++;
SpawnAndStartLevel();
}
reset = false;
}
}
顺便说一下,你是否在FixedUpdate中使用Time.deltaTime或Time.fixedDeltaTime并不重要,如unity docs
中所述请注意,我不会重复计算每次迭代所需的时间,因为在我看来它不会不断变化。但是,如果将reset
设置为true,它将离开该循环并重新计算所需的时间。