C# 每4-5帧随机一次。不是每一帧
我正在做一个学校的项目,一个“玩家”正在靠墙移动。此墙由立方体(1x1x1)制成。这些立方体中有立方体(0.9x0.9x0.9),当玩家靠近它们时,立方体向外移动,朝向玩家 现在,该动画每1帧移动一次。这有点滞后和不自然 我希望此动画每5帧移动一次C# 每4-5帧随机一次。不是每一帧,c#,unity3d,C#,Unity3d,我正在做一个学校的项目,一个“玩家”正在靠墙移动。此墙由立方体(1x1x1)制成。这些立方体中有立方体(0.9x0.9x0.9),当玩家靠近它们时,立方体向外移动,朝向玩家 现在,该动画每1帧移动一次。这有点滞后和不自然 我希望此动画每5帧移动一次 using UnityEngine; using System.Collections; public class InteractiefBlokje : MonoBehaviour { private Transform thePlay
using UnityEngine;
using System.Collections;
public class InteractiefBlokje : MonoBehaviour {
private Transform thePlayer;
private Transform binnenBlokje;
// Use this for initialization
void Start () {
// referentie naar binnenblokje
binnenBlokje = this.gameObject.transform.GetChild(0);
// referentie naar de 'player'
thePlayer = GameObject.FindGameObjectWithTag("Player").transform;
Debug.Log(thePlayer);
}
// Update is called once per frame
void Update () {
Vector3 myPosition = this.transform.position;
Vector3 playerPosition = thePlayer.position;
// afstand tussen player en dit blokje
float distance = Mathf.Clamp(Vector2.Distance(new Vector2(myPosition.x, myPosition.z), new Vector2(playerPosition.x, playerPosition.z)), 0, 50);
// bij afstand 3 -> x = 0.8
// bij afstand 5 -> x = 0
binnenBlokje.position = new Vector3(Random.Range(0, (distance - 5.0f) * -0.4f), this.transform.position.y, this.transform.position.z);
}
}
如果要计算帧数,可以使用计数器,例如:
int FrameCounter = 5;
void Update () {
if (FrameCounter++ % 5 == 0)
{
// your animation goes there
}
}
或
但是,由于每个帧之间存在时间差(FPS可能下降/上升),因此您可能需要使用时间
float timeBetweenAnimations = 0.1f; //0.1 second, arbitrary value
float timer = timeBetweenAnimations;
void Update () {
timer += Time.deltaTime; // increase the timer by the time elapsed since last frame
if (timer >= timeBetweenAnimations)
{
timer = 0; // reset the timer to 0
// your animation goes there
}
}
或者,您可以使用该计时器和速度来定义距离(距离=速度*时间)
给定的帧不是恒定的,希望每5帧看起来是不自然的,这真的很有帮助!
float timeBetweenAnimations = 0.1f; //0.1 second, arbitrary value
float timer = timeBetweenAnimations;
void Update () {
timer += Time.deltaTime; // increase the timer by the time elapsed since last frame
if (timer >= timeBetweenAnimations)
{
timer = 0; // reset the timer to 0
// your animation goes there
}
}
float timer;
float speed = 2.0f; // arbitrary value of 2 units per seconds
void Update () {
timer = Time.deltaTime; // set the timer by the time elapsed since last frame
var direction = new Vector3(...); // the direction you want your object to move, replace the ... by the real vector you need
theObjectToMove.transform.position = direction * speed * timer; // feel free to add a * randomValue to increase/decrease randomly that speed
}