Jump to content

[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]
Photo

how to determine if sprite is on screen?
Started by jmansfield Mar 04 2015 05:20 AM

2 replies to this topic
[TOPIC CONTROLS]
This topic has been archived. This means that you cannot reply to this topic.
[/TOPIC CONTROLS]
[modOptionsDropdown]
[/modOptionsDropdown]
[reputationFilter]
[TOPIC: post.html]
#1

jmansfield

[GLOBAL: userInfoPane.html]
jmansfield
  • Observer

  • 18 posts
  • Corona SDK

how would you determine if a given sprite is on screen or not?



[TOPIC: post.html]
#2

roaminggamer

[GLOBAL: userInfoPane.html]
roaminggamer
  • Corona Geek

  • 7,641 posts
  • Corona SDK

Here are two solutions that both assume the anchorX/anchoY of the object is 0.5.

 

The optimistic version calculates a radius about the object center and assumes it is visible (onscreen) if the object position and radius touch or are within the edge of the screen.


-- True edges of screen (regardless of scaling mode in config.lua)
local left    = 0-(display.actualContentWidth - display.contentWidth)/2
local top     = 0-(display.actualContentHeight - display.contentHeight)/2
local right   = display.contentWidth + (display.actualContentWidth - display.contentWidth)/2
local bottom  = display.contentHeight + (display.actualContentHeight - display.contentHeight)/2

-- Following functions assume anchorX/anchorY == 0.5 (i.e. center)

local function isOnScreenByCenter( obj, buffer )
   buffer = buffer or 0
   if( (obj.x + buffer) > right ) then return false end
   if( (obj.x - buffer) < left) then return false end
   if( (obj.y + buffer) > bottom ) then return false end
   if( (obj.y - buffer) < top ) then return false end
   return true
end

local function isOnScreenOptimistic( obj ) -- Works even for rotated
   local maxRadius = (obj.contentWidth > obj.contentHeight) and obj.contentWidth or obj.contentHeight
   maxRadius = (maxRadius / 2) * math.sqrt(2)
   maxRadius = math.floor( (maxRadius * 10^2) + 0.5) / (10^2)
   if( (obj.x - maxRadius) > right ) then return false end
   if( (obj.x + maxRadius) < left) then return false end
   if( (obj.y + maxRadius) < top ) then return false end
   if( (obj.y - maxRadius) > bottom ) then return false end
   return true
end

Usage:

local tmp = display.newCircle( left, 100, 10)
print( "Is onscreen? ", isOnScreenOptimistic( tmp ) )


[TOPIC: post.html]
#3

jmansfield

[GLOBAL: userInfoPane.html]
jmansfield
  • Observer

  • 18 posts
  • Corona SDK


[topic_controls]
[/topic_controls]