0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ゼロからEntityComponentSystemを書いてみる 2

Last updated at Posted at 2023-04-29

前回はこんなコードを書きました。

main.rs
fn main() {
    
    // idは配列の要素数を表す
    let id = 2;

    let pos_ary = [(0, 0), (0, 0)];

    for i in 0..id  {
        println!("{}: {:?}", i, pos_ary[i])
    }
}

このコードには問題があります。
それは、idが配列の要素数を超えた値のときに実行時エラーになってしまうこと。
つぎに、配列の要素数が固定で、要素を増やせないこと。

この問題に対処しようと思います。
そこで、create_entityという関数を書いてみました。

main.rs
fn main() {
    
    // idは配列の要素数を表す
    let mut id = 0;

    // 配列をやめて、ベクタで宣言する
    let mut pos_ary: Vec<(i32, i32)> = vec![];

    // 効果を確かめるために、10回 create_entity を呼び出す
    for i in 0..10 {
        create_entity(&mut id, &mut pos_ary);
    }

    for i in 0..id  {
        println!("{}: {:?}", i, pos_ary[i])
    }
}

// idを増やして、配列に要素を追加する
fn create_entity(id: &mut usize, ary: &mut Vec<(i32, i32)>){
    *id += 1;
    ary.push((0, 0));
}

このようにすることで、idと配列の要素数を一致させることができました。

ただ、まだ問題があります。
pos_aryの要素がすべて(0, 0)になってしまうこと。
次回は、これを解決したいと思います。

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?