Skip to content

Find nearest object

aubergine10 edited this page Oct 19, 2015 · 1 revision

##Overview

There isn't a function or method to find the closest object, however you can use the range values returned by .GetNearbyObjects() to work it out.

##Example

Let's create a GetNearest( type, range ) function to do the leg work...

-- shortcuts
local find = this.GetNearbyObjects

-- return nearest object, or nil
local function GetNearest( type, range )

  local nearest = { range = math.huge } -- current nearest

  local results = find( type, range ) -- do the search

  -- now find the nearest result
  for object, range in next, results do

    if range < nearest.range then -- this one is nearer
       nearest.range = range
       nearest.object = object
    end

  end

  return nearest.object, ( nearest.object and nearest.range or nil )
end

And here's how to use it (in this example, find the nearest Prisoner entity within a 20 tile radius and kill them; if we don't find one, make a new one and kill that instead):

local prisoner, range = GetNearest( 'Prisoner', 20 )

if prisoner then -- we found nearest prisoner
  prisoner.Damage = 100 -- kill prisoner

else -- we didn't find any prisoners...
  -- ...so let's spawn a new one and kill that instead :P
  prisoner = Object.Spawn( 'Prisoner', this.Pos.x, this.Pos.y )
  prisoner.Damage = 100

end

^ Open "Pages" to Search



Guides:

  • [Lua Basics](Lua Basics Guide)
  • [Save-Load Cycle](Save-Load Cycle Guide)

[Globals](Object Globals):

  • [Game](Game (Global))
  • [me](me (Global))
  • [Object](Object (Global))
  • [this](this (Global))

[Events](Object Events):

Psuedo-Types:

  • [Rotation table](Rotation table)
  • [Id table](Id table)
  • [Location table](Location table)
  • [Velocity table](Velocity table)

[Methods](Object Methods):

[Properties](Object Properties):

Clone this wiki locally