我正在做一个学校项目,其中一个“玩家”正在靠近墙。此墙由立方体(1x1x1)制成。这些立方体中有(0.9x0.9x0.9)的立方体,当玩家旁边移动时,立方体向外移动,朝向玩家。
此动画现在每 1帧移动一次。这有点漫长和不自然。
我希望该动画每 5帧移动一次。
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);
}
}
答案 0 :(得分:2)
好吧,如果要计算帧数,可以使用一个计数器,例如:
int FrameCounter = 5;
void Update () {
if (FrameCounter++ % 5 == 0)
{
// your animation goes there
}
}
或
int FrameCounter = 5;
void Update () {
if (FrameCounter++ >= 5)
{
FrameCounter = 1;
// 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
}
}
或者,您可以使用该计时器和速度来定义距离(距离=速度*时间)
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
}