#graphics #gamedev #game-engine #2d-game #engine #action #pixel

simple_engine_2d

一个非常简单的2D游戏引擎

2个版本

0.1.1 2024年4月15日
0.1.0 2024年3月31日

#985 in 游戏开发

Download history 120/week @ 2024-04-11 15/week @ 2024-04-18 2/week @ 2024-05-30

86 每月下载次数

MIT/Apache

66KB
1.5K SLoC

关于

这是一个为小型2D游戏设计的简单2D游戏引擎。这里没有丰富的功能或独特特性。

入门指南

只需将引擎添加到您新项目的依赖项中,即可准备使用。如果您打算从文件中加载纹理,请务必添加image功能。

工作原理

首先,您需要初始化Application的全局状态。这也是与引擎组件一起工作的必要条件。

接下来,为了显示某些内容,您需要一个Scene。场景允许您响应用户操作,以及定义和控制场景中的SceneItem(绘制在场景中的对象)。可以有多个场景。场景的左上角坐标为(0.0; 0.0),右下角坐标为(1.0; 1.0)

SceneItems位于Scene本身。这是Shape和显示在其上的Texture的组合。Shape在场景中定义一个几何形状,而来自Texture的像素填充空间。

一切设置完毕后,剩下的就是通过Application::run()启动应用程序。

一个简单的示例

让我们创建一个简单的场景,其中有一个带有白色纹理的矩形在周围移动

use simple_engine_2d::*;

struct MyScene {
    my_item: SceneItem<Rect>,
}

impl MyScene {
    fn new() -> MyScene {
        // create a Shape with origin at top-left corner and 1/5 of size of scene
        let rect = Rect::new(0.0, 0.0, 0.2, 0.2);
        // create a Texture from an array of white opaque pixels (10x10)
        let texture = Texture::new(TextureDescriptor {
            width: 10,
            height: 10,
            pixels: Box::new([Color::WHITE; 10 * 10]),
            pixel_access: false,
            filter: TextureFilterMode::Linear,
        });
        // create a SceneItem from them
        MyScene {
            my_item: SceneItem::new(texture, rect),
        }
    }
}

impl Scene for MyScene {
    fn draw(&'static self, context: &mut DrawContext) {
        self.my_item.draw(context);
    }

    fn key_pressed(&'static mut self, key: KeyCode) {
        let rect: &mut Rect = self.my_item.shape_mut();
        let is_moved = match key {
            KeyCode::ArrowLeft => {
                rect.origin.move_by(-0.1, 0.0);
                true
            }
            KeyCode::ArrowRight => {
                rect.origin.move_by(0.1, 0.0);
                true
            }
            KeyCode::ArrowUp => {
                rect.origin.move_by(0.0, -0.1);
                true
            }
            KeyCode::ArrowDown => {
                rect.origin.move_by(0.0, 0.1);
                true
            }
            _ => false,
        };
        if is_moved {
            self.my_item.commit_shape_changes();
        }
    }
}

fn main() {
    Application::initialize(AppInitParams::default());
    Application::add_scene(MyScene::new());
    Application::run();
}

依赖项

~4–39MB
~631K SLoC