#Moving 2d Camera with player

1 messages · Page 1 of 1 (latest)

proper thicket
#

Hi guys. so far i have two functions in my player.rs, one function is to spawn the player, and then the other is to handle the player movement. I spawn the player camera with the 2d camera bundle, but how do i make the camera actually follow the player around? I want the player to be in the center of the camera no matter how much you move around. Thanks!

crisp sluice
#

I'm not sure it's the best way, but I got that behavior by moving the camera transform to the player's transform.

#

Ignore the WorldCoordinates stuff, assume it's just a transform:

pub fn move_camera_to_player(
    mut camera: Query<&mut Transform, With<MapCamera>>,
    player_coords: Query<&WorldCoordinates, (With<Player>, Changed<WorldCoordinates>)>
) {
    if let Some(world_coords) = player_coords.get_single().ok() {
        let mut transform = camera.single_mut();
        let current_scale = (*transform).scale;
        let mut new_transform = world_coords.to_transform();
        new_transform.scale = current_scale;
        *transform = new_transform;
    }
}
grand sun
#

I think the 'standard' way to do this is to make the camera a child of the player, so that its transform becomes relative to the player's transform. IIRC it looks something like

commands.spawn_bundle(PlayerBundle).with_children(|parent| {
  parent.spawn_bundle(Camera2DBundle);
});

(Probably not the right bundle names but I'm pretty sure that's the right function name)

scenic summit
#

@grand sun Great, that works for me. I had to set the transform on the camera, so I ended up with


/// Spawn the player into the world
pub fn spawn(mut commands: Commands, tiles: Res<TileMaps>) {
    let position = Position { x: 0, y: 0, z: 1 };
    let transform = Transform::from_translation(position.to_vec3());
    commands
        .spawn(Player)
        .with_children(|parent| {
            parent.spawn(Camera2dBundle {
                transform,
                ..Camera2dBundle::default()
            });
        })
        .insert(SpriteSheetBundle {
            texture_atlas: tiles.map_tiles.clone(),
            transform,
            sprite: TextureAtlasSprite::new(TILE_PLAYER),
            ..Default::default()
        })
        .insert(position);
}