I am new to rust and bevy and I wanted to follow the ball game tutorial: https://github.com/frederickjjoubert/bevy-ball-game/blob/Episode-2/src/main.rs, but when I wanted to spawn the ball it was spawned off-screen. This is the code I used(I've made some changes because I used bevy 0.11):
use bevy::{prelude::*, window::PrimaryWindow};
pub const PLAYER_SPEED: f32 = 500.0;
pub const PLAYER_SIZE: f32 = 64.0;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, (spawn_camera,spawn_player))
.run();
}
#[derive(Component)]
pub struct Player {}
pub fn spawn_player(
mut commands: Commands,
window_query: Query<&Window, With<PrimaryWindow>>,
asset_server: Res<AssetServer>,
) {
let window = window_query.get_single().unwrap();
commands.spawn((
SpriteBundle {
transform: Transform::from_xyz(window.width() / 2.0, window.height() / 2.0, 0.0),
texture: asset_server.load("sprites/ball_blue_large.png"),
..default()
},
Player {},
));
}
pub fn spawn_camera(mut commands: Commands, window_query: Query<&Window, With<PrimaryWindow>>) {
let window = window_query.get_single().unwrap();
commands.spawn(Camera2dBundle {
transform: Transform::from_xyz(window.width() / 2.0, window.height() / 2.0, 0.0),
..default()
});
}
I tried to let the transform of the camera and the player have the default values and then the player spawned in the middle of the screen, as intended, but after that I couldn't keep the player from going off-screen by the method showed in the tutorial. The values of window.width() and window.height() are 1780 and 640 if it somehow helps. When using the default transform, the player spawns at position (32,32) I think, because if I try to move it down or left the confinement works as intended. The code for the confinement function is here: https://github.com/frederickjjoubert/bevy-ball-game/blob/Episode-3/src/main.rs.