amethyst / specs

Specs - Parallel ECS
https://amethyst.github.io/specs/
Apache License 2.0
2.49k stars 219 forks source link

How do I get the Entity that a Component belongs to? #741

Closed eboatwright closed 2 years ago

eboatwright commented 2 years ago

I'm still working on my breakout clone, and I'm working on the blocks now. So, I've got it to where I can access the Block components from the ball system and check the collisions, now I need to delete the Block. How do I get the Entity to delete it?

eboatwright commented 2 years ago

OH! I figured it out! I just take the Entities value in my system, and then in the for() for looping through each entity, I put that in it with it! Here's the code if anyone wants:

struct BallSystem;

impl<'a> System<'a> for BallSystem {
    type SystemData = (
        ReadStorage<'a, Transform>,
        WriteStorage<'a, RigidBody>,
        ReadStorage<'a, Ball>,
        ReadStorage<'a, Paddle>,
        ReadStorage<'a, Block>,
        Entities<'a>,
    );

    fn run(&mut self, (transform, mut rigidbody, ball, paddle, block, entities): Self::SystemData) {
        for (e_transform, e_rigidbody, e_ball) in (&transform, &mut rigidbody, &ball).join() {
            if is_key_pressed(KeyCode::Space)
            && e_rigidbody.velocity == Vec2::ZERO {
                e_rigidbody.velocity = vec2(e_ball.move_speed, -e_ball.move_speed);
            }

            if e_transform.position.x < 0.0
            || e_transform.position.x > SCREEN_WIDTH as f32 - 13.0 {
                e_rigidbody.velocity.x *= -1.0;
            }

            if e_transform.position.y < 0.0 {
                e_rigidbody.velocity.y *= -1.0;
            }

            for (p_transform, _p_paddle) in (&transform, &paddle).join() {
                if e_transform.position.y + 13.0 > p_transform.position.y
                && e_transform.position.x + 13.0 > p_transform.position.x
                && e_transform.position.x < p_transform.position.x + 80.0 {
                    e_rigidbody.velocity.y *= -1.0;
                }
            }

            for (entity, b_transform, b_block) in (&entities, &transform, &block).join() {
                if e_transform.position.x + 13.0 > b_transform.position.x {
                    entities.delete(entity).unwrap();
                }
            }
        }
    }
}