Fork me on GitHub

Field of Vision

Table of Contents

FOV calculation in Py2D is handled by the py2d.FOV.Vision class. It manages obstructor data and caching for the vision polygon.

Obstructor data is passed as a list of line strips, i.e. a list of lists of Vectors:

>>> obstructors = [
... 	[ Vector(1,3), Vector(3, 4), ... ],
...	[ Vector(4,10), Vector(7,5), ... ],
... ]

If you want to specify polygons as obstructors, you have to close the line strips manually by adding the first Vector to the end of the list.

With the obstructor data at hand, you can create a new Vision object:

>>> vision = Vision(obstructors)

So far, Py2D has no special handling for moving obstructors - just re-set the obstructors using the set_obstructors method on the Vision instance. Right now, the obstructor data is write-only since it will be converted into a more computationally efficient representation.

Updating the Field of Vision

Everytime your scene changes, you will want to calculate a new vision polygon. To do so, you need the eye position and a boundary polygon with a given radius.

In this example, we will create a 16-point polygon around the eye position as our boundary polygon and give it our vision radius as a radius:

>>> boundary = Polygon.regular(eye, radius, 16)

We can then get the vision polygon like this:

>>> vision = vision.get_vision(eye, radius, boundary)

FOV for tile-based maps

If you are creating a game with tiled maps, the py2d.FOVConverter package might interest you. It contains a converter for generic tile-based maps into obstructor data that can be used for Vision objects.

For example, if you have a map data structure in map with

you can generate obstructor data like this:

>>> blocking_function = lambda x,y: map.get_block_light(x,y)
>>> obstructors = convert_tilemap(
...	map.width, map.height, 
...	blocking_function, 
...	tile_width, tile_height
... )