Game Development Reference
In-Depth Information
theObject:setReferencePoint(refPt)
theObject.x = xPos
theObject.y = yPos
end
--
local back
local function zoomer(event)
local phase = event.phase
local target=event.target
if phase=="began" then
display.currentStage:setFocus(target)
transition.to( back,{time=200,xScale=0.5, yScale=0.5} )
elseif phase=="ended" then
display.currentStage:setFocus(nil)
transition.to( back,{time=200,xScale=1, yScale=1} )
end
end
--
back = display.newGroup()
local wallpaper = display.newImage( back, "wallpaper.jpg", 0, 0, true )
local i
for i=1, 10 do
local rect = display.newRect( back, i*50, i*50, 40, 40 )
rect:setFillColor( 255-(i*10), 0, 0 )
end
position ( back, _W/2, _H/2, display.CenterReferencePoint )
local button = display.newRect( 10, 400, 50, 50 )
button:setFillColor(255,0,0,100)
button:addEventListener( "touch", zoomer )
There are some interesting new API features that we have used; let's look at them first before
discussing how it all works together.
Each of the display objects has a dimension; this is accessible to us via code using the
height
and
width
properties. When we scale the object, the dimensions do not change. However, visually the
object changes size based on the scaling factor. So, if we have a rectangle that is 100 pixels in
width and we scale it by setting
xScale
to 0.5, the width of the rectangle still remains 100, but on the
screen it looks smaller—50 pixels. When we need to get the size of this object on the screen,
width
does not return the correct size. This is where
contentWidth
and
contentHeight
come in handy.
These two properties reflect the actual dimensions of the object with the scaling applied. This is
available for every display object. The
display
namespace also has
contentHeight
and
contentWidth
properties, which correspond to the device screen size.
display.contentWidth
would return 320 for
iPhone 3, 640 for iPhone 4, and 768 for the iPad.
At the start of the program, we save the values of the screen size in the variables
_H
and
_W
; these
are then used throughout the program as the width and height of the device screen.
We can position an object by simply manipulating the x and y members. However, each time we
change the x- or the y-coordinate, the object's reference position is set to center (i.e., the object
is centered around this position). This causes extra lines of code where you have to set the x- and
y-coordinates and then set
referencePoint
to
TopLeft
. The best way to manage this is to have a