1个不稳定版本

0.0.1 2024年5月26日

#58#shape

GPL-3.0-or-later

19KB
502

欢迎使用Realms - 轻量级Rust游戏库!

Realms是一个库,允许您轻松使用Rust制作游戏、动画和任何2D图形。

这是一个“中等级别”的包,它提供了一个非常简单的API,可以轻松地将图形窗口绘制出来,而不会像典型的游戏引擎那样臃肿。Realms是一个游戏库

入门

首先,使用cargo new <project_name>创建一个新的项目。

接下来,通过在您的Cargo.toml中添加以下行将Realms导入到您的Rust项目中

realms = "VERSION_NUMBER"

VERSION_NUMBER替换为最新的Realms版本(显示在上文)。或者,从您的项目目录中在终端运行此命令

cargo new project_name

project_name替换为您要创建的游戏的名称。

最后,将以下代码添加到src/main.rs文件中

use realms::event::Event;
use realms::window::Window
use realms::Colour;

fn main()
{
  let mut window = Window::new("My Amazing Game", 800, 450).unwrap();  // Create a new `Window`. For now, we won't worry about error handling.
  let fill_colour = Colour::from_rgb(0, 100, 255);  // Stores the background colour of the window.
  let mut running = true;  // Keep looping until this is `false`.

  while running
  {
    window.fill(fill_colour.clone()).unwrap();  // Copy the fill_colour so we can use it again on the next iteration.
    for event in window.get_events()
    {
      match event
      {
        Event::Quit => {
          running = false;  // Stop the loop if the user closes the program.
        },
        _ => {  }  // Default, do nothing if the event doesn't match.
      }
    }
    window.draw();  // Draw the frame.
  }
}

使用cargo run运行此代码将给出以下结果

An 800x450 window with title "My Amazing Game" and filled with a blue background

恭喜!您已经成功编写了您的第一个Realms游戏 :)

注意:有关更多信息,请参阅github.com/dylanopen/realms中的完整说明。

示例:形状和事件

到目前为止,我们只填充了背景颜色。如果我们想绘制一些形状怎么办?

在这个示例中,我们将构建一个程序,屏幕上的矩形将跟随鼠标指针。

将此代码复制到您的main.rs文件中

use realms::event::Event;
use realms::shape::Rect;
use realms::window::Window;
use realms::Colour;

fn main()
{
  let mut window = Window::new("Shapes and events", 800, 600).unwrap();
  let mut running = true;

  let mut mouse_x = 400;  // Rectangle starting position.
  let mut mouse_y = 600;  // Must be mutable so we can update it.
  
  while running
  {
    window.fill(Colour::from_rgb(255, 255, 255)).unwrap();  // white
    for event in window.get_events()
    {
      match event
      {
        Event::Quit => {
          running = false;
        },
        Event::MouseMotion(event) => {
          mouse_x = event.x;  // Update mouse position.
          mouse_y = event.y;  // `event` is a MouseMotionEvent struct: it also holds the current mouse position.
        },
        _ => {  }
      }
    }
    let rect = Rect::new(
      mouse_x-16, mouse_y-16,  // The coordinates represent the top-left of the rect. Subtracting 16 ensures the rectangle's centre is at the mouse position.
      32, 32,
      Colour::from_rgb(255, 100, 0)  // orange
    );
    rect.draw(&mut window).unwrap();  // Draw the rectangle to the window. Realms uses `object.draw(&mut window)` notation.
    window.draw();
  }
}

运行程序后,您应该会看到一个橙色的矩形跟随光标!

注意:有关更多信息,请参阅github.com/dylanopen/realms中的完整说明。

文档

上述示例只是对Realms库的非常简要介绍。

请查看GitHub上的文档。在docs.rs上也有一些信息,尽管那里的文档有限。

感谢您选择Realms来构建您下一个伟大的游戏!

依赖关系

~16MB
~345K SLoC