【发布时间】:2019-08-18 19:45:07
【问题描述】:
我正在尝试在 Web 程序集中创建游戏。我选择在 rust 中准备它并使用 cargo-web 编译它。我设法获得了一个有效的游戏循环,但由于生锈借用机制,我在添加 MouseDownEvent 侦听器时遇到了问题。我非常喜欢编写“安全”代码(不使用“不安全”关键字)
此时游戏只是将一个红色框从 (0,0) 移动到 (700,500),速度取决于距离。我希望下一步使用用户点击更新目的地。
这是游戏的简化和工作代码。
静态/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Game!</title>
</head>
<body>
<canvas id="canvas" width="600" height="600">
<script src="game.js"></script>
</body>
</html>
src/main.rs
mod game;
use game::Game;
use stdweb::console;
use stdweb::traits::*;
use stdweb::unstable::TryInto;
use stdweb::web::document;
use stdweb::web::CanvasRenderingContext2d;
use stdweb::web::html_element::CanvasElement;
use stdweb::web::event::MouseDownEvent;
fn main()
{
let canvas: CanvasElement = document()
.query_selector("#canvas")
.unwrap()
.unwrap()
.try_into()
.unwrap();
canvas.set_width(800u32);
canvas.set_height(600u32);
let context = canvas.get_context().unwrap();
let game: Game = Game::new();
// canvas.add_event_listener(|event: MouseDownEvent|
// {
// game.destination.x = (event.client_x() as f64);
// game.destination.y = (event.client_y() as f64);
// });
game_loop(game, context, 0f64);
}
fn game_loop(mut game : Game, context : CanvasRenderingContext2d, timestamp : f64)
{
game.cycle(timestamp);
draw(&game,&context);
stdweb::web::window().request_animation_frame( |time : f64| { game_loop(game, context, time); } );
}
fn draw(game : &Game, context: &CanvasRenderingContext2d)
{
context.clear_rect(0f64,0f64,800f64,800f64);
context.set_fill_style_color("red");
context.fill_rect(game.location.x, game.location.y, 5f64, 5f64);
}
src/game.rs
pub struct Point
{
pub x: f64,
pub y: f64,
}
pub struct Game
{
pub time: f64,
pub location: Point,
pub destination: Point,
}
impl Game
{
pub fn new() -> Game
{
let game = Game
{
time: 0f64,
location: Point{x: 0f64, y: 0f64},
destination: Point{x: 700f64, y: 500f64},
};
return game;
}
pub fn cycle(&mut self, timestamp : f64)
{
if timestamp - self.time > 10f64
{
self.location.x += (self.destination.x - self.location.x) / 10f64;
self.location.y += (self.destination.y - self.location.y) / 10f64;
self.time = timestamp;
}
}
}
main.rs 中被注释掉的部分是我添加 MouseDownEvent 监听器的尝试。不幸的是它会产生编译错误:
error[E0505]: cannot move out of `game` because it is borrowed
--> src\main.rs:37:15
|
31 | canvas.add_event_listener(|event: MouseDownEvent|
| - ----------------------- borrow of `game` occurs here
| _____|
| |
32 | | {
33 | | game.destination.x = (event.client_x() as f64);
| | ---- borrow occurs due to use in closure
34 | | game.destination.y = (event.client_y() as f64);
35 | | });
| |______- argument requires that `game` is borrowed for `'static`
36 |
37 | game_loop(game, context, 0f64);
| ^^^^ move out of `game` occurs here
我非常想知道如何正确实现将用户输入读取到游戏中的方法。它不需要是异步的。
【问题讨论】:
标签: events rust webassembly game-loop