LoginSignup
2
0

More than 5 years have passed since last update.

1秒間に60回"poi"をプリントするコード書いた

Last updated at Posted at 2018-05-10

序文

現在Rustで弾幕ゲームをむちむち作っている。
そこで1秒間に60回の処理をするコードが必要になったから書いた。
このコードを使うことで、60FPSなゲームを作ることができる。

概要

特に目新しい事はない。

時間を計測開始
-> 何らかの処理
-> 経過した時間と1/60秒の差分だけsleepさせる。
-> 最初に戻る

また時間計測は標準ライブラリのstd::time、sleepは標準ライブラリのstd::threadを使った。

コード

play rust-lang: https://play.rust-lang.org/?version=stable&mode=release

//#![feature(duration_extras)]
use std::time::*;
// Instant::now()
use std::thread::*;
// sleep()

const FPS: u64 = 60; //set frame per second

struct Fps {
    start: Instant,
    count: u64,
    fps: f64,
}

impl Fps {
    fn new() -> Fps {
        Fps {
            start: Instant::now(),
            count: 0,
            fps: 0.0,
        }
    }

    fn update(&mut self) {
        if self.count == FPS {
            let start_time = self.start.elapsed().subsec_nanos() as f64 * 1e-9;
            self.fps = 1.0 / start_time;
            self.count = 0;
        }
        self.start = Instant::now();
        self.count += 1;
    }

    fn wait(&self) {
        //let one_frame_sec: Duration = Duration::from_nanos(0_016_000_000);
        let one_frame_sec: Duration = Duration::from_millis(0_016);
        let sleep_time: Duration = one_frame_sec - self.start.elapsed();
        sleep(sleep_time);
    }
}
fn main() {
    let mut fps = Fps::new();

    for c in 0..3001 {
        &fps.update();
        //println!("fps: {}", fps.fps);
        //println!("count: {}", fps.count);
        //let start =
        //    fps.start.elapsed().as_secs() as f64 + fps.start.elapsed().subsec_nanos() as f64 * 1e-9;
        //println!("start time: {}\n", start);
        println!("poi");
        &fps.wait();
    }
}

  • Duration::from_nanos()はstableでは動かず、nigtlyでも#![feature(duration_extras)]を書かないとエラーになる。

参考文献

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0