Skip to main content

hello/
hello.rs

1//! The README's first scene: a cube that turns on its own and goes where you click.
2//!
3//! ```text
4//! cargo run --example hello
5//! ```
6use codecraft::ecs::Entity;
7use codecraft::glam::Vec3;
8use codecraft::prelude::*;
9use codecraft::{Light, OrbitCamera, Transform, gizmos, primitives};
10
11struct Hello {
12    cube: Entity,
13}
14
15impl Hello {
16    // Builds the scene with the app in hand, and keeps what it will touch later.
17    fn new(app: &mut AppState) -> Self {
18        app.spawn(gizmos::grid());
19
20        // Lights are entities; a scene that spawns none has none.
21        app.spawn_entity((
22            Light::default()
23                .from(Vec3::new(-0.55, 1.0, -0.45))
24                .temperature(4200.0)
25                .strength(2.2)
26                .angle(1.5),
27            Light::object("Key Light"),
28        ));
29        app.spawn_entity((
30            Light::default()
31                .from(Vec3::new(1.0, 0.35, 0.1))
32                .temperature(9500.0)
33                .strength(1.5)
34                .angle(0.0)
35                .shadow(false),
36            Light::object("Rim Light"),
37        ));
38
39        let cube = app.spawn_entity(
40            primitives::Box::cube(1.0)
41                .name("Cube")
42                .color(Color::srgb(0.9, 0.45, 0.2))
43                .transform(Transform::at(0.0, 0.5, 0.0)),
44        );
45
46        // Right-drag orbits, middle-drag pans, WASD walks, the wheel dollies.
47        app.spawn_entity(OrbitCamera::new(Vec3::new(0.0, 0.5, 0.0), 5.0));
48
49        Hello { cube }
50    }
51}
52
53impl Scene for Hello {
54    fn update(&mut self, app: &mut AppState) {
55        // Runs every frame: turn the cube with the clock.
56        let turn = app.time().elapsed * 0.6;
57        app.edit::<Transform>(self.cube, |transform| transform.set_yaw(turn));
58
59        // A click on the ground sends the cube there.
60        if app.mouse().just_pressed
61            && let Some(hit) = app.cursor_ray().plane_hit(0.0)
62        {
63            app.edit::<Transform>(self.cube, |transform| {
64                transform.translation = hit + Vec3::Y * 0.5;
65            });
66        }
67    }
68}
69
70fn main() {
71    App::new("hello").scene(Hello::new).run();
72}