我當前的玩家移動代碼0.32會在每次按鍵時提供翻譯。
如果它很快被點擊了 2 次,它應該是0.64.
我用協程提供這個,但它受 fps 的影響。
如何確保它不受 fps 影響?
我知道,但是如果我乘以Time.deltaTime我怎么得到呢?0.32Time.deltaTime
我當前的移動代碼:
public float move = 0.32f; //movement limitation
public float repeat = 4; // I perform 0.32 in 4 parts to be more smooth.
void Update()
{
if (Input.GetKeyDown(KeyCode.LeftArrow) //Exapmle key. I have 4 ways to move
{
StartCoroutine("Left");
}
}
IEnumerator Left()
{
for (int i = 1; i <= repeat; i )// as I said, I perform 0.32 in 4 parts to be more smooth.
{
transform.position = transform.position new Vector3(-move / repeat, 0, 0);
yield return null;
}
}
uj5u.com熱心網友回復:
如果您想保持平穩,請使用固定速度并執行例如
// distance to move
public float move = 0.32f;
// speed in Unity units per second
public float speed = 1f;
void Update()
{
if (Input.GetKeyDown(KeyCode.LeftArrow)
{
StartCoroutine(Left);
}
}
IEnumerator Left()
{
// Pre-calculate the target position
// This is the huge advantage of IEnumerators -> you can store local variables over multiple frames
var targetPosition = transform.position Vector3.left * move;
// track how far you have already moved
var moved = 0f;
// Loop until you moved enough
while(moved < move)
{
// the step is now frame-rate independent and moves the object with a fixed value per second
var step = speed * Time.deltaTime;
// every frame move one such step towards the target without overshooting
transform.position = Vector3.MoveTowards(transform.position, targetPosition, step);
// keep track of the movement
moved = step;
yield return null;
}
// and to end up with a clean value in the end
transform.position = targetPosition;
}
然而
如果點擊 2 次很快,應該是 0.64
這不會被覆寫。為了做到這一點,我實際上會使用完全不同的方法,根本沒有協程,而是簡單地使用例如
// distance to move
public float move = 0.32f;
// speed in Unity units per second
public float speed = 1f;
Vector3 targetPosition;
void Start()
{
targetPosition = transform.position;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.LeftArrow)
{
targetPosition = Vector3.left;
}
...
transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
}
因此,現在您可以隨心所欲地朝任何方向粉碎您的移動鍵,它將簡單地將它們全部匯總到一個中targetPosition,并始終以固定的速度平穩地朝它移動。
or another alternative would be to interpolate and rather make the object move faster if it is further away from the target but slower the closer it comes
// 5 here is an arbitrary number based on experience -> tweak it according to your needs
public float interpolation = 5f;
...
transform.position = Vector3.Lerp(transform.position, targetPosition, interpolation * Time.deltaTime);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/424489.html
