How to make a camera follow a entity/component?

(Johan Bjäreholt) #1

So I am prototyping a 3D platformer where I have a Character entity with a Character component and a Camera entity with a CharacterCamera component.

I am trying to make a CharacterCameraSystem which should make the Camera entity follow the Character entity.
A way to solve this would be to make a System which on each frame takes the position of the camera and writes it into the Character struct, but I wonder if there is any way to take the data straight from the transform component of the same entity which has the character component? (Would seem more efficient and cleaner that way)
Or maybe there’s some completely different way to solve this issue which I’m missing?

pub struct CharacterCameraSystem;

impl<'s> System<'s> for CharacterCameraSystem {
    type SystemData = (
        ReadStorage<'s, CharacterCamera>,
        WriteStorage<'s, Transform>,
        ReadStorage<'s, Character>,
    );

    fn run(&mut self, (cameras, mut transforms, characters): Self::SystemData) {
        println!("test1");
        for (transform, camera) in (&mut transforms, &cameras).join() {
            println!("test2");
            transform.set_z (20.0);  // Replace this with code to follow the character
        }
    }
}

I hope this question makes sense.

0 Likes

(Joël Lupien) #2

On the camera entity, add a Parent component with your character entity as the parent.

1 Like

(Johan Bjäreholt) #3

Works well and was very simple to use, thank you!

0 Likes