Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use bevy::input::mouse::MouseMotion;
- use bevy::prelude::*;
- use bevy::window::CursorGrabMode;
- #[derive(Component)]
- struct Player;
- #[derive(Component)]
- struct CameraSpeed(f32);
- fn main() {
- App::new()
- .insert_resource(Msaa::Sample4)
- .add_plugins(DefaultPlugins.set(WindowPlugin {
- primary_window: Some(Window {
- title: "Zombie Mayhem".into(),
- mode: bevy::window::WindowMode::Fullscreen,
- ..Default::default()
- }),
- ..Default::default()
- }))
- .add_systems(Startup, setup)
- .add_systems(Update, (cursor_grab_system, look_y))
- .run();
- }
- fn setup(
- mut commands: Commands,
- mut meshes: ResMut<Assets<Mesh>>,
- mut materials: ResMut<Assets<StandardMaterial>>,
- ) {
- //floor
- commands.spawn(PbrBundle {
- mesh: meshes.add(Mesh::from(shape::Plane::from_size(16.0))),
- material: materials.add(Color::rgb(1., 0.9, 0.9).into()),
- transform: Transform::from_xyz(0., 0., 0.),
- ..Default::default()
- });
- //Cube
- commands.spawn(PbrBundle {
- mesh: meshes.add(Mesh::from(shape::Cube::new(1.))),
- material: materials.add(Color::rgb(1., 0.9, 0.9).into()),
- transform: Transform::from_xyz(0., 2., -10.),
- ..Default::default()
- });
- // light
- commands.spawn(PointLightBundle {
- point_light: PointLight {
- intensity: 1500.0,
- shadows_enabled: true,
- ..default()
- },
- transform: Transform::from_xyz(4.0, 8.0, 4.0),
- ..default()
- });
- // Player
- commands
- .spawn((Player, Transform::from_xyz(0., 0., 0.)))
- .with_children(|parent| {
- parent
- .spawn(Camera3dBundle {
- transform: Transform::from_xyz(0., 4., 0.0),
- ..Default::default()
- })
- .insert(CameraSpeed(4.));
- });
- }
- fn cursor_grab_system(
- mut windows: Query<&mut Window>,
- btn: Res<Input<MouseButton>>,
- key: Res<Input<KeyCode>>,
- ) {
- for mut window in &mut windows {
- if btn.just_pressed(MouseButton::Left) {
- // if you want to use the cursor, but not let it leave the window,
- // use `Confined` mode:
- window.cursor.grab_mode = CursorGrabMode::Confined;
- // also hide the cursor
- window.cursor.visible = false;
- }
- if key.just_pressed(KeyCode::Escape) {
- window.cursor.grab_mode = CursorGrabMode::None;
- window.cursor.visible = true;
- }
- }
- }
- fn look_y(
- mut cam_query: Query<(&mut Transform, &CameraSpeed, &Parent), With<Camera3d>>,
- mut player_query: Query<&mut Transform, Without<Camera3d>>,
- windows: Query<&Window>,
- mut mouse_event: EventReader<MouseMotion>,
- time: Res<Time>,
- ) {
- for (mut cam, spd, parent) in &mut cam_query {
- let mut player = player_query.get_mut(parent.get()).unwrap();
- for window in &windows {
- if !window.cursor.visible {
- for event in mouse_event.read() {
- println!("X:{} Y:{}", event.delta.x, event.delta.y);
- // Rotate by mouse movement
- player.rotate_y(-event.delta.x * spd.0 * time.delta_seconds());
- cam.rotate_x(-event.delta.y * spd.0 * time.delta_seconds());
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment