Christopher Angell
Christopher Angell

Reputation: 51

How to prevent the camera from seeing through walls in Bevy?

Using Bevy, I made a 3d maze, but when I try to navigate the maze, the camera can see through the walls. Looking down a corridor, the wall ahead will appear but as it gets closer, it just cuts off and I can see through to the other corridor.

I am using Box sprites for the walls as so:

commands
    .spawn(PbrBundle {
        mesh: meshes.add(Mesh::from(shape::Box::new(1.0, 1.0, 0.1))),
        material: materials.add(Color::rgb(0.8, 0.7, 0.6).into()),
        transform: Transform::from_translation(Vec3::new(x, 0.5, y+0.5)),
        ..Default::default()
    });

and my camera is added as so:

commands
    .spawn(Camera3dBundle {
        transform: Transform::from_translation(Vec3::new(-2.0, 0.5, 0.0))
            .looking_at(Vec3::new(0.0, 0.5, 0.0), Vec3::unit_y()),
        ..Default::default()
    })

Is there anything extra I need to do to the perspective to prevent it from seeing through objects that are too close to it? Ideally it would never see through objects.

Upvotes: 1

Views: 420

Answers (1)

Christopher Angell
Christopher Angell

Reputation: 51

Turns out that my walls were spaced exactly 1 unit apart, and the default nearfield perspective is 1.0. Decreasing the near parameter of the perspective on the camera to 0.01 prevented seeing through the walls when too close to them.

in main.rs:

use bevy_render::camera::PerspectiveProjection;

commands
    .spawn(Camera3dBundle {
        transform: Transform::from_translation(Vec3::new(-2.0, 0.5, 0.0))
            .looking_at(Vec3::new(0.0, 0.5, 0.0), Vec3::unit_y()),
        perspective_projection: PerspectiveProjection {
            near: 0.01,
            ..Default::default()
        },
        ..Default::default()
    })

in cargo.toml:

[dependencies]
bevy_render = "0.4"

Upvotes: 2

Related Questions