Thursday, June 6, 2013

Random Movement Corona SDK

Want to know how to program some random movement?

--Innermost and outermost points for display.
local xMin = display.screenOriginX
local yMin = display.screenOriginY
local xMax = display.contentWidth - display.screenOriginX
local yMax = display.contentHeight - display.screenOriginY

--Pre-declare math function for SPEED
local mRand = math.random

--Pre-declare the points that will be generated each time move() is called
local newX
local newY

--Create our object that will fly around
local dot = display.newCircle(50,50,10)

--Function to move
local function move()
--Create new Random point to move to inside screen limits
    newX = mRand(xMin,xMax)
    newY = mRand(yMin,yMax)
--transition the dot to those points   
    transition.to(dot, {x = newX, y = newY})
end
--move dot every half second infinitely
timer.performWithDelay(500, move, 0)

So let's talk about what's going on here. We create a circle and tell it to move to a random point. We also delay it 500ms so we can see it move. Then with the 0 that means move() will be called infinitely with that delay. This could be useful for any sort of game that needs an easy AI.

Also note that by using the points around the edges of the screen, this program will work perfectly on every device.

3 comments:

  1. Hello, thanks for the great code. I'm a Corona newbie and I'm trying this piece of code in my project, but do you know a way for the dot to move way slower? I'm trying to implement a fish graphic wandering around in an aquarium.

    Thanks again.

    ReplyDelete
  2. Hello Santabla,
    The line [ transition.to(dot, {x = newX, y = newY}) ] in the move() function tells the dot to move and at what speed. There is a parameter for speed, however, I left it out. In order to change the speed to a slower one it would look like this.

    transition.to (dot, {time = 1500, x = newX, y = newY})

    However, I have another post that talks about how this won't make the fish move at the same speed. It only slows the time the fish takes to get to a location.

    If you combine the code from this post, and the math from here http://appajuice.blogspot.com/2013/06/moving-object-at-constant-rate-corona.html

    You should figure it out!

    I've actually cancelled my corona membership, so you'll have to do some investigating on your own.

    ReplyDelete