Reputation: 37
I've used Camera2dBundle to import sprites and backgrounds into the scene I'm setting up. But I'm not sure how to move the camera independently of the sprite movements. Basically I don't want the camera to follow the player. I want it to constantly move in a single direction regardless of user input. I've tried:
fn move_camera(mut camera: Query<&mut Transform, With<Camera>>) {
for mut transform in camera.iter_mut() {
transform.translation.x += 5.0;
}
However this moves the player's x position
I see transform is made of these items:
Transform { translation: Vec3(0.0, 0.0, 999.9), rotation: Quat(0.0, 0.0, 0.0, 1.0), scale: Vec3(1.0, 1.0, 1.0) }
Here's how I'm accepting user input:
if keyboard_input.pressed(KeyCode::Right) {
transform.translation.x += 2.0 * 5.0;
transform.rotation = Quat::from_rotation_y(0.0).into();
*atlas = player.run.clone();
Is there a better way to do this? Can I add an item to transform? Or what modification can I make?
Upvotes: 3
Views: 5995
Reputation: 6146
I can't tell from your question what went wrong on your side, but here is how I just set up a camera that moves independently in the x axis and follows the player in the y axis:
use crate::{CameraMarker, PlayerMarker};
use bevy::prelude::*;
pub fn camera_movement_system(
player_query: Query<&Transform, With<PlayerMarker>>,
// The `Without` is necessary so bevy knows the player and camera are not the same component.
mut camera_query: Query<&mut Transform, (With<CameraMarker>, Without<PlayerMarker>)>,
) {
// I have only one camera
let mut camera_transform = camera_query.single_mut();
// I have only one player
let player_transform = player_query.single();
// x-Axis: always move to the right
camera_transform.translation.x += 5.0;
// Set the y-Axis camera position to the player position
camera_transform.translation.y = player_transform.translation.y;
}
This snippet expects that you have everything set up already. If you are not using Marker Components, it should also work with Camera
instead of CameraMarker
.
Upvotes: 0
Reputation: 37
Solved it. Not really the answer I wanted, but simply adding a movement for the player in the opposite directions works.
// added
transform.translation.x -= -1.0 * 5.0;
//
if keyboard_input.pressed(KeyCode::Right)
transform.translation.x += 2.0 * 5.0;
transform.rotation =
Quat::from_rotation_y(0.0).into();
*atlas = player.run.clone();
Upvotes: -1