Pixel Vision 8 CalculateIndex() Lua Tutorial

Converts an X and Y position into an index value. This is useful for finding positions in 1D arrays that represent 2D data.

Usage

CalculateIndex ( x, y, width )

Arguments

NameValueDescription
xintThe x position.
yintThe y position.
widthintThe width of the data if it was represented as a 2D array.

Returns

ValueDescription
intReturns an int value representing the X and Y position in a 1D array.

CalculateIndex Example

In this example, we will treat a 1D as a 2D array and get a value from it based on an X, Y position.

Running this code will output the following:

CalculateIndexOutput_image_0.png

Learn more about making Pixel Vision 8 games by checking out the docs.

Step 1

Create a new file called code.lua.{1} in your project folder.

Step 2

Create a new local variable called exampleGrid inside the script:

01 local exampleGrid = {
02 "A", "B", "C",
03 "D", "E", "F",
04 "G", "H", "I",
05 }

A 1D array of example values

Step 3

Create a new function called Init():

06 function Init()
07 
08 end

Step 4

Add the following code to the script:

07   DrawText("CalculateIndex()", 8, 8, DrawMode.TilemapCache, "large", 15)
08   DrawText("Lua Example", 8, 16, DrawMode.TilemapCache, "medium", 15, -4)

Example Title

Step 5

Create a new local variable called index inside the script:

09   local index = CalculateIndex(1, 1, 3)

Calculate the center index based on a grid with 3 columns

Step 6

Add the following code to the script:

10   DrawText("Position 1,1 is Index " .. index .. " is " .. exampleGrid[index], 1, 4, DrawMode.Tile, "large", 15)

Draw the index and value to the display

Step 7

Create a new function called Draw():

12 function Draw()
13 
14 end

Step 8

Add the following code to the script:

13   RedrawDisplay()

Redraw the display

Final Code

When you are done, you should have the following code in the code.lua file:

01 local exampleGrid = {
02 "A", "B", "C",
03 "D", "E", "F",
04 "G", "H", "I",
05 }
06 function Init()
07   DrawText("CalculateIndex()", 8, 8, DrawMode.TilemapCache, "large", 15)
08   DrawText("Lua Example", 8, 16, DrawMode.TilemapCache, "medium", 15, -4)
09   local index = CalculateIndex(1, 1, 3)
10   DrawText("Position 1,1 is Index " .. index .. " is " .. exampleGrid[index], 1, 4, DrawMode.Tile, "large", 15)
11 end
12 function Draw()
13   RedrawDisplay()
14 end