外观
相机
Camera2D 提供一个以目标点为中心的 2D 相机:
以下示例直接使用全局函数。
rust
pub struct Camera2D {
pub target: Vec2, // 屏幕中心对应的世界坐标
pub zoom: f32, // 缩放,默认 1.0
pub rotation: f32, // 旋转,弧度
}使用
rust
// 世界层
let camera = Camera2D::new(Vec2::new(player.x, player.y))
.with_zoom(1.5)
.with_rotation(0.1);
set_camera(camera);
draw_circle(0.0, 0.0, 40.0, ORANGE); // 世界坐标 (0, 0)
// 回到默认相机绘制 HUD
set_default_camera();
draw_text("HUD", 20.0, 20.0, 24.0, WHITE);set_camera之后绘制的图元使用该相机。set_default_camera恢复“世界坐标 = 屏幕逻辑坐标”的模式。- 相机在绘制时被烘焙进图元实例,因此一帧内可以切换相机,世界层与 UI 层互不影响。
构造
rust
Camera2D::default() // target = (0, 0), zoom = 1, rotation = 0
Camera2D::new(Vec2::new(100.0, 50.0))
Camera2D::at(100.0, 50.0)
Camera2D::new(Vec2::ZERO).with_zoom(0.5).with_rotation(1.0)可交互示例
rust
struct State {
camera: Camera2D,
}
fn main() {
let state = State { camera: Camera2D::default() };
cici::run_state(state, |state| {
let dt = dt();
let mut pan = Vec2::ZERO;
if is_key_down(Key::A) { pan.x -= 1.0; }
if is_key_down(Key::D) { pan.x += 1.0; }
if is_key_down(Key::W) { pan.y -= 1.0; }
if is_key_down(Key::S) { pan.y += 1.0; }
if pan.length_squared() > 0.0 {
state.camera.target += pan.normalize() * 520.0 * dt / state.camera.zoom;
}
let wheel = mouse_wheel().y;
if wheel != 0.0 {
state.camera.zoom = (state.camera.zoom * (1.0 + wheel * 0.12)).clamp(0.2, 6.0);
}
if is_key_down(Key::Q) { state.camera.rotation += dt * 1.5; }
if is_key_down(Key::E) { state.camera.rotation -= dt * 1.5; }
clear(hex(0x0a0f18));
set_camera(state.camera.clone());
for i in -10..=10 {
let x = i as f32 * 100.0;
draw_line(x, -1000.0, x, 1000.0, 2.0, hex(0x1a2740));
}
draw_circle(0.0, 0.0, 50.0, ORANGE);
set_default_camera();
draw_text("WASD 平移 · 滚轮缩放 · Q/E 旋转", 20.0, 20.0, 20.0, WHITE);
});
}屏幕坐标转世界坐标
鼠标位置始终是屏幕逻辑坐标。使用相机时,可以手动反变换:
rust
let center = Vec2::new(screen_width(), screen_height()) * 0.5;
let screen = mouse_position();
let world = camera.target
+ (screen - center).rotated(-camera.rotation) / camera.zoom;注意事项
rotation使用弧度,不是角度。zoom必须为正数;为 0 会导致图元不可见。- 相机只影响绘制,不改变输入坐标系;输入仍然是屏幕坐标。
- 文本、纹理、形状都会被相机统一变换。