Reputation:
I'm building a small video game. I'm trying to do good oop/design.
I have a map object and a camera object. These are both created in the 'world' object.
There is a problem though. In the map I render and update everything. For performance reasons I only want to update/render what is only on the player's screen.
The camera object has this information - but the map object can't get to it.
There is a couple ways I could get this information, but wanted to get an option on how to do it.
Upvotes: 1
Views: 315
Reputation: 5782
I would personally update everything, even if it is not in the view just so that when something does come into view it is already at its position. As for the rendering, you could always implement your own version of draw() or paint() methods to only draw things that are seen by the camera. It would just be some sort of simple algorithm.
Upvotes: 0
Reputation: 10007
The OO principle that is probably most pertinent here is the Single Responsibility Principle.
Consider these statements of responsibility:
Map
object is responsible for holding the layout of the worldCamera
object is responsible for maintaining a viewpoint that is used to observe the worldGiven that, having the Map
be responsible for rendering what's on-screen is clearly outside its jurisdiction.
You should probably have a WorldRenderer
, which should take in both a Map
and a Camera
in order to render a screen.
While we're on the subject of good design, you might also want to make the WorldRenderer
immutable in nature - it will take in a Map
and Camera
upon construction, and from that point on, those references can't be changed, e.g.:
public class WorldRenderer {
private final Map map;
private final Camera camera;
private final List<LightSource> lightSources;
public WorldRenderer(Map map, Camera camera, List<LightSource> sources) {
this.map = map;
this.camera = camera;
this.lightSources = sources;
}
public void render() {
Viewport viewport = camera.getViewport();
Map submap = map.getVisibleMapFor(viewport);
Scene litScene = applyLighting(submap); // using lightSources
renderScene(litScene);
}
private void renderScene(Scene scene) {
...
}
}
... you might have noticed that the example provides some light sources as well. Again, that's using SRP to decouple the rendering process from its component elements.
Upvotes: 7