Skip to content

Getting objects

Ben Cragg edited this page Apr 5, 2019 · 3 revisions

Tile layers are great for drawing images, however you'll often want to prevent your player passing certain areas. Collision detection should be done with an object layer.

In the following example we get an object layer by name, then iterate through the objects checking the shapes:

package main

func main() {
  // Do not ignore errors normally!
  m, _ := tilepix.Read("MyMap.tmx")

  var rectangles []pixel.Rect
  var circles []pixel.Circle

  for _, obj := range m.GetObjectLayerByName("Object Layer 1").Objects {
    fmt.Println(obj)

    if obj.GetType() == tilepix.RectangleObj {
      r, _ := obj.GetRect()
      rectangles = append(rectangles, r)
    }

    if obj.GetType() == tilepix.EllipseObj {
      c, _ := obj.GetEllipse()
      circles = append(circles, c)
    }
  }

  fmt.Printf("Rectangles: %v\n", rectangles)
  fmt.Printf("Circles: %v\n", circles)
}

If you have objects with a specific name you'd like to retrieve, this can be done both at map level and at the object layer level:

// Get objects with the name "tree" from any object layer in the map
objs := m.GetObjectByName("tree")
// Get objects with the name "tree" from the object layer named "collisions"
objs2 := m.GetObjectLayerByName("collisions").GetObjectByName("tree")

Note that object names in Tiled don't have to be unique, so these functions will return a slice of every object with a matching name.

Clone this wiki locally