use ggez::event::{self, EventHandler};
use ggez::graphics::{self, Color, DrawParam, Rect};
use ggez::{Context, ContextBuilder, GameResult};
use std::time::Duration;
struct MainState {
rotation: f32,
}
impl MainState {
fn new() -> GameResult<MainState> {
let s = MainState { rotation: 0.0 };
Ok(s)
}
}
impl EventHandler for MainState {
fn update(&mut self, _ctx: &mut Context) -> GameResult<()> {
// 每次更新增加旋轉角度,旋轉速度為每秒 1 弧度
self.rotation += 1.0 * 0.016;
if self.rotation > 2.0 * std::f32::consts::PI {
self.rotation -= 2.0 * std::f32::consts::PI;
}
Ok(())
}
fn draw(&mut self, ctx: &mut Context) -> GameResult<()> {
// 清除畫面(黑色)
graphics::clear(ctx, Color::BLACK);
// 建立一個白色的方形,大小為 100x100
let rectangle =
graphics::Mesh::new_rectangle(ctx, graphics::DrawMode::fill(), Rect::new(-50.0, -50.0, 100.0, 100.0), Color::WHITE)?;
// 取得畫面中間的位置
let (width, height) = graphics::drawable_size(ctx);
let dest_point = [width / 2.0, height / 2.0];
// 繪製方形,設定旋轉角度,並將繪製原點設在方形中心 (-50, -50 offset 達到中心點)
graphics::draw(
ctx,
&rectangle,
DrawParam::default()
.dest(dest_point)
.rotation(self.rotation)
.offset([0.5, 0.5]), // 將旋轉中心設在方形中心
)?;
graphics::present(ctx)
}
}
fn main() -> GameResult {
let (mut ctx, event_loop) = ContextBuilder::new("rotating_square", "author")
.build()
.expect("Failed to build ggez context");
let state = MainState::new()?;
event::run(ctx, event_loop, state)
}