首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >每4-5帧随机一次。不是每一帧

每4-5帧随机一次。不是每一帧
EN

Stack Overflow用户
提问于 2019-04-10 10:19:59
回答 1查看 94关注 0票数 1

我正在做一个学校项目,在那里,一个“玩家”正在靠近墙壁移动。这面墙是由立方体(1x1x1)构成的。这些立方体中有立方体(0.9x0.9x0.9),当玩家在他们旁边移动时,这些立方体向外移动。

这个动画现在移动每一个1帧。这是有点滞后和不自然。

我希望这个动画移动每一个5帧

代码语言:javascript
复制
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);
    }
}
EN

回答 1

Stack Overflow用户

发布于 2019-04-10 10:24:49

如果您想要计算帧,可以使用计数器,例如:

代码语言:javascript
复制
int FrameCounter = 5;

void Update () {
    if (FrameCounter++ % 5 == 0)
    {
        // your animation goes there
    }
}

代码语言:javascript
复制
int FrameCounter = 5;

void Update () {
    if (FrameCounter++ >= 5)
    {
        FrameCounter = 1;
        // your animation goes there
    }
}

但是,由于每个帧之间存在时间差(FPS可以下降/增加),所以您可能需要使用时间。

代码语言:javascript
复制
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
    }
}

或者,可以使用定时器和速度来定义距离(距离=速度*时间)

代码语言:javascript
复制
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
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55610126

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档