Pixel Vision 8 CalculatePosition() Lua Tutorial
Converts an index value into a point with an X
and Y
value to help when working with 1D arrays that represent 2D data.
Usage
CalculatePosition ( index, width )
Arguments
Name | Value | Description |
index | int | The position of the 1D array. |
width | int | The width of the data if it was a 2D array. |
## Returns
Value | Description |
int | Returns a vector representing the X and Y position of an index in a 1D array. |
CalculatePosition Example
In this example, we will treat a 1D as a 2D array and convert an index into a X
, Y
position.
Running this code will output the following:
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("CalculatePosition()", 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 = 4
Step 6
Create a new local
variable called position
inside the script
:
10 local position = CalculatePosition(index, 3)
Calculate the center index based on a grid with 3 columns
Step 7
Add the following code to the script
:
11 DrawText("Position " .. position.x .. ",".. position.y .. " at Index " .. index .. " is " .. exampleGrid[index], 1, 4, DrawMode.Tile, "large", 15)
Draw the index and value to the display
Step 8
Create a new function
called Draw()
:
13 function Draw()
14
15 end
Step 9
Add the following code to the script
:
14 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("CalculatePosition()", 8, 8, DrawMode.TilemapCache, "large", 15)
08 DrawText("Lua Example", 8, 16, DrawMode.TilemapCache, "medium", 15, -4)
09 local index = 4
10 local position = CalculatePosition(index, 3)
11 DrawText("Position " .. position.x .. ",".. position.y .. " at Index " .. index .. " is " .. exampleGrid[index], 1, 4, DrawMode.Tile, "large", 15)
12 end
13 function Draw()
14 RedrawDisplay()
15 end