❼ 添加第二个控制台图层,这个控制台没有背景色,所以透明部分可以穿过它。
这段代码创建了一个终端窗口,它包含两个控制台图层,一个用来绘制地图,另一个用来绘制玩家角色。后续的实现中并不会一次性渲染整个地图——为了限制视窗的大小,你需要使用摄像机。
摄像机好比游戏世界中的一个窗口,定义了地图中当前可见的区域。接下来要做的是,创建一个新文件 camera.rs ,然后导入 prelude ,最后创建一个结构体,结构体包含足够多的信息用来描述摄像机的视场边界:
use crate::prelude::*; pub struct Camera { pub left_x : i32, pub right_x : i32, pub top_y : i32, pub bottom_y : i32 }
开发者需要创建一个摄像机,并且能够在玩家角色移动时更新摄像机的参数。因为摄像机的视窗是以玩家角色为中心的,因此需要玩家的位置信息来实现上述两个功能:
impl Camera { pub fn new(player_position: Point) -> Self { Self{ left_x : player_position.x - DISPLAY_WIDTH/2, right_x : player_position.x+DISPLAY_WIDTH/2, top_y : player_position.y - DISPLAY_HEIGHT/2, bottom_y : player_position.y+DISPLAY_HEIGHT/2 } } pub fn on_player_move(&mut self, player_position: Point) { self.left_x=player_position.x - DISPLAY_WIDTH/2; self.right_x=player_position.x+DISPLAY_WIDTH/2; self.top_y=player_position.y - DISPLAY_HEIGHT/2; self.bottom_y=player_position.y+DISPLAY_HEIGHT/2; } }
这里的 new() 和 on_player_move() 函数基本上是一样的,它们定义了以玩家角色为中心的可视窗口。从窗口中能够看到的最左侧的图块坐标,是玩家的 x 坐标减去窗口宽度的一半;能看到的最右侧的图块的 x 坐标,则是玩家的 x 坐标加上窗口宽度的一半。 y 轴上的计算和 x 轴是一样的,只不过要使用窗口的高度来计算。
在 main.rs 中,导入 camera 模块,并将 camera 结构体加入 prelude 里面:
mod camera; mod prelude { ... pub use crate::camera::*; }
接下来把摄像机添加到游戏状态中:
struct State { map: Map, player: Player, ➤ camera: Camera }
下一步,更新游戏状态结构体的 new 函数,使得它能够初始化摄像机:
fn new() -> Self { let mut rng= RandomNumberGenerator::new(); let map_builder=MapBuilder::new(&mut rng); Self { map : map_builder.map, player: Player::new(map_builder.player_start), ➤ camera: Camera::new(map_builder.player_start) } }
5.6.4 用摄像机来渲染地图
此处你需要更新 map.rs 里面的 render() 函数,让这个函数可以配合摄像机的位置来工作:
pub fn render(&self, ctx: &mut BTerm, camera: &Camera) { ctx.set_active_console(0); for y in camera.top_y..camera.bottom_y { for x in camera.left_x..camera.right_x { if self.in_bounds(Point::new(x, y)) { let idx=map_idx(x, y); match self.tiles[idx] { TileType::Floor => { ctx.set( x - camera.left_x, y - camera.top_y, WHITE, BLACK, to_cp437('.') ); } TileType::Wall=> { ctx.set( x - camera.left_x, y -camera.top_y, WHITE, BLACK, to_cp437('#') ); } } } } } }
评论 0条