Skip to content

Instantly share code, notes, and snippets.

@twe4ked
Created August 31, 2020 01:47
Show Gist options
  • Save twe4ked/1a606e58cc6df8725e1632c37dde7d99 to your computer and use it in GitHub Desktop.
Save twe4ked/1a606e58cc6df8725e1632c37dde7d99 to your computer and use it in GitHub Desktop.
use crate::entities::player::Player;
use bevy::input::{keyboard::KeyCode, Input};
use bevy::prelude::*;
use bevy::render::camera::Camera;
const PLAYER_SPEED: f32 = 500.0;
const PADDING: f32 = 100.0;
pub fn player_movement_system(
time: Res<Time>,
windows: Res<Windows>,
keyboard_input: Res<Input<KeyCode>>,
mut player_query: Query<(&Player, &mut Translation)>,
mut camera_query: Query<(&Camera, &mut Translation)>,
) {
let (height, width) = {
let window = windows.get_primary().expect("no window");
(window.height as f32, window.width as f32)
};
for (_player, mut translation) in &mut player_query.iter() {
let mut direction = Vec3::zero();
if keyboard_input.pressed(KeyCode::Left) {
direction -= Vec3::new(1.0, 0.0, 0.0);
}
if keyboard_input.pressed(KeyCode::Right) {
direction += Vec3::new(1.0, 0.0, 0.0);
}
if keyboard_input.pressed(KeyCode::Down) {
direction -= Vec3::new(0.0, 1.0, 0.0);
}
if keyboard_input.pressed(KeyCode::Up) {
direction += Vec3::new(0.0, 1.0, 0.0);
}
let delta = time.delta_seconds * direction * PLAYER_SPEED;
translation.0 += delta;
// NOTE: This won't work once a UI camera is added
for (_camera, mut camera_translation) in &mut camera_query.iter() {
// Left edge
if translation.0.x() - camera_translation.0.x() < -(width / 2.0) + PADDING {
camera_translation.0 += delta;
}
// Right edge
if translation.0.x() - camera_translation.0.x() > (width / 2.0) - PADDING {
camera_translation.0 += delta;
}
// Bottom edge
if translation.0.y() - camera_translation.0.y() < -(height / 2.0) + PADDING {
camera_translation.0 += delta;
}
// Top edge
if translation.0.y() - camera_translation.0.y() > (height / 2.0) - PADDING {
camera_translation.0 += delta;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment