how to apply force to a random object?

I know there’s an easy answer to this but I can’t figure it out! I have five objects and I want to randomly select one of those objects and apply force to it. This is what I have, but it won’t work:

[lua]local i = math.random( 1, 5 ) – choose a random number from 1 to 5
object_[i]:applyForce( 10 ) – apply force to the randomly chosen object[/lua]

The error I get is “attempt to index global ‘object_’ (a nil value)”. I’ve already declared the objects as global. What am I doing wrong?
[import]uid: 82194 topic_id: 28447 reply_id: 328447[/import]

I’m not entirely sure about what is going on without some more code given.

But what i do suggest is making a couple fuction so

local function randomForce()
if i == 1 then
object1:applyForce(10)
end
then just do the same with the other objects

i did something similar and doing this worked fine.

-just my 3 cents :slight_smile:
[import]uid: 113909 topic_id: 28447 reply_id: 114883[/import]

Did you actually create an array called ‘object_’ to contain the objects? Also, did you add a physics body to the objects?

This code will create five rectangles, place them into an array, and a force can then be applied to an object at random by calling randomForce().

[lua]

local physics = require “physics”
physics.start()

local objects = {}
local randomForce = function ()

local i = math.random(1, 5)

local obj = objects[i]

obj:applyForce (10, 5, obj.x, obj.y)
end

local createObjects = function ()

for a = 1, 5, 1 do

local obj = display.newRect(a*60, a*60, 50, 50)

physics.addBody(obj, “static”, {density = 1, friction = 0.5, bounce = 0.3} )

objects[a] = obj

end
end
createObjects()

randomForce()[/lua] [import]uid: 93133 topic_id: 28447 reply_id: 114903[/import]