Tile Collision Detection - lua

So, I have been working on this game for a bit. However, over the past day I have not been able to figure out how to work my collision detection.
The scale at default is equal to 2.
The player is 41*scale by 64*scale.
My player is centered in the middle of the screen in both the x and y axis.
Since the player is centered the world is what moves, those variables are worldx and worldy. The player always stays at the center of the screen.
My tile map is stored in an array and is based on the image pixel color. If the pixel is white at map[x][y] the value is set to 0 else it's set to the block. Meaning the block does not get rendered.
for x = 0, w-1 do --scans the image and builds the map array
amap[x] = {}
for y = 0, h-1 do
local r, g, b, a = source:getPixel(x, y)
if r == 255 and g == 255 and b == 255 then
block = 0
end
if r == 255 and g == 100 and b == 0 then
block = 1
end
if r == 130 and g == 125 and b == 0 then
block = 2
end
if r == 76 and g == 76 and b == 76 then
block = 3
end
if r == 255 and g == 0 and b == 255 then
--this is the spawn pixel yet to build
end
amap[x][y] = block
end
end --end function
function that draws the map
for x = 0, w-1 do --draws the map
for y = 0, h-1 do
if amap[x][y] ~= 0 then
love.graphics.drawq(ImgBlocks, Blocks[amap[x][y]], 32*x*(3/bscale) + worldx, 32*y*(3/bscale) + worldy + jy, 0 , 3/bscale, 3/bscale)
end
if amap[x][y] == 4 then
end
end
end --end function
The function needs to return true or false base on if there is collision between player and block.

Your tiles are 32x32, correct? (from the drawq call) I would recommend you make a function that checks if a point is in a solid tile:
function pointCollisionTest(x, y)
-- find which tile the point is in
local tx, ty = math.floor(x / 32), math.floor(y / 32)
-- check the tile
if map[tx][ty] == solid then
return true
else
return false
end
end
You'll have to change the if map[x][y] == solid logic based on how you determine solid tiles, but this code should otherwise work.
Once you have point collision, the way you make the player collide is by checking each corner of its hitbox (which you should easily be able to determine) against this function whenever the player moves. There are a few ways to do this; I use the relatively simple method of calculating the player's new position, testing it, then canceling the move entirely if the collision test returns true. You have to check/cancel the x and y components of the move separately, though, so the player can move along walls instead of sticking to them.

Are you asking for a basic 2d collision detection?
A simplified formula:
if (playerx > blockminx) and (playery < blockmaxx) and (playery > blockminy) and (playery < blockmaxy) then collission

Related

Trying to write a recursive program that reveals all adjacent tiles that are blank

I'm trying to make a clone of minesweeper. In that game, there is a feature that, whenever you click an empty box, all adjacent empty tiles are revealed and empty tiles adjacent to those empty tiles are also revealed.
Right now when I tried to implement this, it only reveals the 8 adjacent tiles of the tile I clicked, not any other empty tiles which are next to the empty tiles revealed
Here is the code that I'm running right now (it has 2 parameters row and col):
local rowCords = {row-16, row, row+16}
local colCords = {col-16, col, col+16}
--Check surroundings
for r = 1, 3, 1 do
for c = 1, 3, 1 do
curRow = rowCords[r]
curCol = colCords[c]
if (curRow >= 16 and curRow <= 400 and curCol >= 16 and curCol <= 176) then
if boardCords[Board:getBox(curRow, curCol)].value == 1 then
boardCords[Board:getBox(curRow, curCol)].revealed = true
end
end
end
end
In your algorithm you are checking only 9 tiles, but you must do this recursively for checked tiles. So your algorithm must be like:
function revealTile(row, col)
if (row >= 16 and row <= 400 and col >= 16 and col <= 176) then
local tile = boardCords[Board:getBox(row, col)]
-- Try to reveal tile
if not tile.revealed and tile.value == 1 then
tile.revealed = true
-- Try to reveal surroundings
for r = row-16,row+16,16 do
for c = col-16,col+16,16 do
revealTile(r, c)
end
end
end
end
end

Attempt to index field (a nil value), for an Object

I have a problem with trying to add things to a LOVE2D version of Match-3. (From the CS50 course)
I added a function swapTiles() into my Board class and made a class object called self.board in a Class called PlayState. Then when I try to access the new function, it says this error:
Error
src/states/PlayState.lua:155: attempt to index field 'board' (a nil value)
I'll provide my Board and PlayState class below:
Board: (keep in mind the new function is literally in the code)
Board = Class{}
function Board:init(x, y, level) -- Added "level" as an integer for the block variations.
self.x = x
self.y = y
self.matches = {}
self.level = level
self:initializeTiles()
end
function Board:swapTiles(tile1, tile2)
-- swap grid positions of tiles
local tempX = tile1.gridX
local tempY = tile1.gridY
tile1.gridX = tile2.gridX
tile1.gridY = tile2.gridY
tile2.gridX = tempX
tile2.gridY = tempY
-- swap tiles in the tiles table
self.tiles[tile1.gridY][tile1.gridX] = tile1
self.tiles[tile2.gridY][tile2.gridX] = tile2
end
function Board:initializeTiles()
self.tiles = {}
-- There should only be two shiny tiles.
for tileY = 1, 8 do
-- empty table that will serve as a new row
table.insert(self.tiles, {})
for tileX = 1, 8 do
self.isPowerup = false
if math.random(1, 25) == 4 then
self.isPowerup = true
end
-- create a new tile at X,Y with a random color and variety
table.insert(self.tiles[tileY], Tile(tileX, tileY, math.random(18), math.min(8, math.random(1, self.level)), self.isPowerup))
end
end
while self:calculateMatches() do
-- recursively initialize if matches were returned so we always have
-- a matchless board on start
self:initializeTiles()
end
end
--[[
Goes left to right, top to bottom in the board, calculating matches by counting consecutive
tiles of the same color. Doesn't need to check the last tile in every row or column if the
last two haven't been a match.
]]
function Board:calculateMatches()
local matches = {}
-- how many of the same color blocks in a row we've found
local matchNum = 1
-- horizontal matches first
for y = 1, 8 do
local colorToMatch = self.tiles[y][1].color
matchNum = 1
-- every horizontal tile
for x = 2, 8 do
-- if this is the same color as the one we're trying to match...
if self.tiles[y][x].color == colorToMatch then
matchNum = matchNum + 1
else
-- set this as the new color we want to watch for
colorToMatch = self.tiles[y][x].color
-- if we have a match of 3 or more up to now, add it to our matches table
if matchNum >= 3 then
local match = {}
-- go backwards from here by matchNum
for x2 = x - 1, x - matchNum, -1 do
-- add each tile to the match that's in that match
table.insert(match, self.tiles[y][x2])
-- Shiny Check
if self.tiles[y][x2].isShiny == true then
for i = 1, 8 do
table.insert(match, self.tiles[y][i])
end
end
end
-- add this match to our total matches table
table.insert(matches, match)
end
-- don't need to check last two if they won't be in a match
if x >= 7 then
break
end
matchNum = 1
end
end
-- account for the last row ending with a match
if matchNum >= 3 then
local match = {}
-- go backwards from end of last row by matchNum
for x = 8, 8 - matchNum + 1, -1 do
table.insert(match, self.tiles[y][x])
end
table.insert(matches, match)
end
end
-- vertical matches
for x = 1, 8 do
local colorToMatch = self.tiles[1][x].color
matchNum = 1
-- every vertical tile
for y = 2, 8 do
if self.tiles[y][x].color == colorToMatch then
matchNum = matchNum + 1
else
colorToMatch = self.tiles[y][x].color
if matchNum >= 3 then
local match = {}
for y2 = y - 1, y - matchNum, -1 do
table.insert(match, self.tiles[y2][x])
if self.tiles[y2][x].isShiny == true then
for i = 1, 8 do
table.insert(match, self.tiles[i][x])
end
end
end
table.insert(matches, match)
end
matchNum = 1
-- don't need to check last two if they won't be in a match
if y >= 7 then
break
end
end
end
-- account for the last column ending with a match
if matchNum >= 3 then
local match = {}
-- go backwards from end of last row by matchNum
for y = 8, 8 - matchNum, -1 do
table.insert(match, self.tiles[y][x])
end
table.insert(matches, match)
end
end
-- store matches for later reference
self.matches = matches
-- return matches table if > 0, else just return false
return #self.matches > 0 and self.matches or false
end
--[[
Remove the matches from the Board by just setting the Tile slots within
them to nil, then setting self.matches to nil.
]]
function Board:removeMatches()
for k, match in pairs(self.matches) do
for k, tile in pairs(match) do
self.tiles[tile.gridY][tile.gridX] = nil
end
end
self.matches = nil
end
--[[
Shifts down all of the tiles that now have spaces below them, then returns a table that
contains tweening information for these new tiles.
]]
function Board:getFallingTiles()
-- tween table, with tiles as keys and their x and y as the to values
local tweens = {}
-- for each column, go up tile by tile till we hit a space
for x = 1, 8 do
local space = false
local spaceY = 0
local y = 8
while y >= 1 do
-- if our last tile was a space...
local tile = self.tiles[y][x]
if space then
-- if the current tile is *not* a space, bring this down to the lowest space
if tile then
-- put the tile in the correct spot in the board and fix its grid positions
self.tiles[spaceY][x] = tile
tile.gridY = spaceY
-- set its prior position to nil
self.tiles[y][x] = nil
-- tween the Y position to 32 x its grid position
tweens[tile] = {
y = (tile.gridY - 1) * 32
}
-- set space back to 0, set Y to spaceY so we start back from here again
space = false
y = spaceY
spaceY = 0
end
elseif tile == nil then
space = true
if spaceY == 0 then
spaceY = y
end
end
y = y - 1
end
end
-- create replacement tiles at the top of the screen
for x = 1, 8 do
for y = 8, 1, -1 do
local tile = self.tiles[y][x]
-- if the tile is nil, we need to add a new one
if not tile then
local tile = Tile(x, y, math.random(18), math.random(1, self.level))
tile.y = -32
self.tiles[y][x] = tile
tweens[tile] = {
y = (tile.gridY - 1) * 32
}
end
end
end
return tweens
end
function Board:getNewTiles()
return {}
end
function Board:testForMatches()
for y = 1, 8 do
for x = 1, 8 do
-- Test for left swap
if x > 1 then
end
end
end
end
function Board:render()
for y = 1, #self.tiles do
for x = 1, #self.tiles[1] do
self.tiles[y][x]:render(self.x, self.y)
end
end
end
Here's my PlayState: (look for PlayState:swapTiles(), keep in mind that the self.board is being used several times for and works fine, except when i try calling self.board:swapTiles().)
PlayState = Class{__includes = BaseState}
function PlayState:init()
-- start our transition alpha at full, so we fade in
self.transitionAlpha = 255
-- position in the grid which we're highlighting
self.boardHighlightX = 0
self.boardHighlightY = 0
-- timer used to switch the highlight rect's color
self.rectHighlighted = false
-- flag to show whether we're able to process input (not swapping or clearing)
self.canInput = true
-- tile we're currently highlighting (preparing to swap)
self.highlightedTile = nil
self.score = 0
self.timer = 60
-- set our Timer class to turn cursor highlight on and off
Timer.every(0.5, function()
self.rectHighlighted = not self.rectHighlighted
end)
-- subtract 1 from timer every second
Timer.every(1, function()
self.timer = self.timer - 1
-- play warning sound on timer if we get low
if self.timer <= 5 then
gSounds['clock']:play()
end
end)
end
function PlayState:enter(params)
-- grab level # from the params we're passed
self.level = params.level
-- spawn a board and place it toward the right
self.board = params.board or Board(VIRTUAL_WIDTH - 272, 16)
-- grab score from params if it was passed
self.score = params.score or 0
-- score we have to reach to get to the next level
self.scoreGoal = self.level * 1.25 * 1000
end
function PlayState:update(dt)
if love.keyboard.wasPressed('escape') then
love.event.quit()
end
-- go back to start if time runs out
if self.timer <= 0 then
-- clear timers from prior PlayStates
Timer.clear()
gSounds['game-over']:play()
gStateMachine:change('game-over', {
score = self.score
})
end
-- go to next level if we surpass score goal
if self.score >= self.scoreGoal then
-- clear timers from prior PlayStates
-- always clear before you change state, else next state's timers
-- will also clear!
Timer.clear()
gSounds['next-level']:play()
-- change to begin game state with new level (incremented)
gStateMachine:change('begin-game', {
level = self.level + 1,
score = self.score
})
end
if self.canInput then
-- move cursor around based on bounds of grid, playing sounds
if love.keyboard.wasPressed('up') then
self.boardHighlightY = math.max(0, self.boardHighlightY - 1)
gSounds['select']:play()
elseif love.keyboard.wasPressed('down') then
self.boardHighlightY = math.min(7, self.boardHighlightY + 1)
gSounds['select']:play()
elseif love.keyboard.wasPressed('left') then
self.boardHighlightX = math.max(0, self.boardHighlightX - 1)
gSounds['select']:play()
elseif love.keyboard.wasPressed('right') then
self.boardHighlightX = math.min(7, self.boardHighlightX + 1)
gSounds['select']:play()
end
-- if we've pressed enter, to select or deselect a tile...
if love.keyboard.wasPressed('enter') or love.keyboard.wasPressed('return') then
-- if same tile as currently highlighted, deselect
local x = self.boardHighlightX + 1
local y = self.boardHighlightY + 1
-- if nothing is highlighted, highlight current tile
if not self.highlightedTile then
self.highlightedTile = self.board.tiles[y][x]
-- if we select the position already highlighted, remove highlight
elseif self.highlightedTile == self.board.tiles[y][x] then
self.highlightedTile = nil
-- if the difference between X and Y combined of this highlighted tile
-- vs the previous is not equal to 1, also remove highlight
elseif math.abs(self.highlightedTile.gridX - x) + math.abs(self.highlightedTile.gridY - y) > 1 then
gSounds['error']:play()
self.highlightedTile = nil
else
self:swapTiles(self.highlightedTile, self.board.tiles[y][x], true)
end
end
end
Timer.update(dt)
end
function PlayState:swapTiles(tile1, tile2, swapBackAtNoMatch)
local tile1 = tile1
local tile2 = tile2
local swapBackAtNoMatch = swapBackAtNoMatch
self.board:swapTiles(tile1, tile2) -- Causes the nil error.
if swapBackAtNoMatch then
-- tween coordinates between two swapping tiles
Timer.tween(0.1, {
[tile1] = {x = tile2.x, y = tile2.y},
[tile2] = {x = tile1.x, y = tile1.y}
})
-- once they've swapped, tween falling blocks
:finish(function ()
local matches = self.board:calculateMatches()
if matches then
self.calculateMatches(matches)
else
-- swap back if there's no match
self.swapTiles(tile1, tile2, false)
gSounds['error']:play()
end
end)
else
-- tween coordinates between the two so they swap
Timer.tween(0.1, {
[tile1] = {x = tile2.x, y = tile2.y},
[tile2] = {x = tile1.x, y = tile1.y}})
end
end
--[[
Calculates whether any matches were found on the board and tweens the needed
tiles to their new destinations if so. Also removes tiles from the board that
have matched and replaces them with new randomized tiles, deferring most of this
to the Board class.
]]
function PlayState:calculateMatches()
self.highlightedTile = nil
-- if we have any matches, remove them and tween the falling blocks that result
local matches = self.board:calculateMatches()
if matches then
gSounds['match']:stop()
gSounds['match']:play()
-- add score for each match
for k, match in pairs(matches) do
local varietyPoints = 0 -- We'll keep track of the bonus variety points here
-- We'll use vareity to calculate points for each tile within a match
for j, tiles in pairs(match) do
varietyPoints = varietyPoints + tiles.variety * 25
end
self.score = self.score + (#match * 50) + varietyPoints
-- Also add one second times the number of match to the timer
self.timer = self.timer + #match * 1
end
-- remove any tiles that matched from the board, making empty spaces
self.board:removeMatches()
-- gets a table with tween values for tiles that should now fall
local tilesToFall = self.board:getFallingTiles()
-- first, tween the falling tiles over 0.25s
Timer.tween(0.25, tilesToFall):finish(function()
local newTiles = self.board:getNewTiles()
-- then, tween new tiles that spawn from the ceiling over 0.25s to fill in
-- the new upper gaps that exist
Timer.tween(0.25, newTiles):finish(function()
-- recursively call function in case new matches have been created
-- as a result of falling blocks once new blocks have finished falling
self:calculateMatches()
end)
end)
-- if no matches, we can continue playing
else
self.canInput = true
end
end
Honestly doesn't make much sense. Please help!
function PlayState:swapTiles(tile1, tile2, swapBackAtNoMatch) end
is syntactic sugar for
PlayState.swaptiles = function(self, tile1, tile2, swapBackAtNoMatch) end
That's the reason why you can work with self inside that function.
A function defined like that needs to be called using the colon operator as well to make this work. Or you explicitly provide the table as first parameter.
Hence in your call self.swapTiles(tile1, tile2, false)
self is going to be tile1
tile1.board is nil so self.board is nil in this function call which causes the error
You have to call self:swapTiles(tile1, tile2, false) or self.swapTiles(self, tile1, tile2, false)
Please make sure you fully understand the colon syntax.

How to use bounding box in Love2d?

I've been using some extremely bulky code to detect collision between simple objects, and I've heard about bounding boxes. I can't find any tutorials on how to use it, so I'm asking about how to use it. Here is how I detect collision:
function platform.collision()
if player.x + player.width / 2 <= platform.x + platform.width and
player.x + player.width / 2 >= platform.x and
player.y + player.height <= platform.y + platform.height and
player.y + player.height >= platform.y then
The MDN has a rather concise article on 2D collision detection. Being the MDN, the examples are in javascript, but are easily translated to, and applicable in, any language - including Lua.
Let's take a look:
Axis-Aligned Bounding Box
One of the simpler forms of collision detection is between two rectangles that are axis aligned — meaning no rotation. The algorithm works by ensuring there is no gap between any of the 4 sides of the rectangles. Any gap means a collision does not exist.
Their example, translated to Lua:
local rect1 = { x = 5, y = 5, width = 50, height = 50 }
local rect2 = { x = 20, y = 10, width = 10, height = 10 }
if
rect1.x < rect2.x + rect2.width and
rect1.x + rect1.width > rect2.x and
rect1.y < rect2.y + rect2.height and
rect1.height + rect1.y > rect2.y
then
-- collision detected!
end
-- filling in the values =>
if
5 < 30 and
55 > 20 and
5 < 20 and
55 > 10
then
-- collision detected!
end
A live example, again in JavaScript, demonstrates this well.
Here's a quick (and imperfect) Love2D example you can throw into a main.lua and play around with.
local function rect (x, y, w, h, color)
return { x = x, y = y, width = w, height = h, color = color }
end
local function draw_rect (rect)
love.graphics.setColor(unpack(rect.color))
love.graphics.rectangle('fill', rect.x, rect.y,
rect.width, rect.height)
end
local function collides (one, two)
return (
one.x < two.x + two.width and
one.x + one.width > two.x and
one.y < two.y + two.height and
one.y + one.height > two.y
)
end
local kp = love.keyboard.isDown
local red = { 255, 0, 0, 255 }
local green = { 0, 255, 0, 255 }
local blue = { 0, 0, 255, 255 }
local dim1 = rect(5, 5, 50, 50, red)
local dim2 = rect(20, 10, 60, 40, green)
function love.update ()
if kp('up') then
dim2.y = dim2.y - 1
end
if kp('down') then
dim2.y = dim2.y + 1
end
if kp('left') then
dim2.x = dim2.x - 1
end
if kp('right') then
dim2.x = dim2.x + 1
end
dim2.color = collides(dim1, dim2) and green or blue
end
function love.draw ()
draw_rect(dim1)
draw_rect(dim2)
end
Oka explained it very well. This works for everything rectangular, not rotated and axis aligned. And you even already did it that way. This is great for buttons and the like!
But what I like doing is using (invisible) circles around objects and see if these collide. This works for everything where height is about the same as the width (which is the case for many sidescrolling platformers or top-down RPGs).
It's quite handy if you want to have the object centered at the current position. And it's especially helpful to simulate a finger on a touchscreen device, because a finger is quite a bit bigger than a mouse cursor. ;)
Here's an example on how to use this method. You can copy it as an actual game, it'll work.
--[[ Some initial default settings. ]]
function love.load()
settings = {
mouseHitbox = 5, -- A diameter around the mouse cursor.
-- For a finger (thouchscreen) this could be bigger!
}
objects = {
[1] = {
x = 250, -- Initial X position of object.
y = 200, -- Initial Y position of object.
hitbox = 100, -- A diameter around the CENTER of the object.
isHit = false -- A flag for when the object has been hit.
},
[2] = {
x = 400,
y = 250,
hitbox = 250,
isHit = false
}
}
end
--[[ This is the actual function to detect collision between two objects. ]]
function collisionDetected(x1,y1,x2,y2,d1,d2)
-- Uses the x and y coordinates of two different points along with a diameter around them.
-- As long as these two diameters collide/overlap, this function returns true!
-- If d1 and/or d2 is missing, use the a default diameter of 1 instead.
local d1 = d1 or 1
local d2 = d2 or 1
local delta_x = x2 - x1
local delta_y = y2 - y1
local delta_d = (d1 / 2) + (d2 / 2)
if ( delta_x^2 + delta_y^2 < delta_d^2 ) then
return true
end
end
--[[ Now, some LÖVE functions to give the collisionDetection() some context. ]]
function love.draw()
for i=1,#objects do -- Loop through all objects and draw them.
if ( objects[i].isHit ) then
love.graphics.setColor(255, 0, 0) -- If an object is hit, it will flash red for a frame.
objects[i].isHit = false
else
love.graphics.setColor(255, 255, 255)
end
love.graphics.circle("line", objects[i].x, objects[i].y, objects[i].hitbox/2)
end
end
-- You can use the following to check, if any object has been clicked on (or tapped on a touch screen device).
function love.mousepressed(x,y,button)
if ( button == 1 ) then
local i = objectIsHit(x,y) -- Check, if an object has been hit.
if ( i ) then
-- The object number 'i' has been hit. Do something with this information!
objects[i].isHit = true
end
end
end
function objectIsHit(x,y)
for i=1,#objects do -- Loop through all objects and see, if one of them has been hit.
if ( collisionDetected(x, y, objects[i].x, objects[i].y, settings.mouseHitbox, objects[i].hitbox) ) then
return i -- This object has been hit!
end
end
end
-- For the sake of completeness: You can use something like the following to check, if the objects themselves collide.
-- This would come in handy, if the objects would move around the screen and then bounce from each other, for example.
function love.update(dt)
if ( collisionDetected(objects[1].x, objects[1].y, objects[2].x, objects[2].y, objects[1].hitbox, objects[2].hitbox) ) then
-- The objects collided. Do something with this information!
end
end
As you can see, the collisionDetection() function is quite easy and intuitive to use.
Hopefully I could give you some more insight. And have fun with LÖVE 2D! :)

Lua Love2d Write Code Instance Once, Use Multiple Times With Each One Being Unique

I have asked a question similar to this, but i was asking it for Processing.JS. Now i am making something out of LOVE2D Lua, what I'm trying to do is that i have a button where when clicked it adds a circle on-screen. I already have code that when i click and hold on the circle, i can move it around. But when i add a second circle, they both are using he same variables. I want it so i write once instance of the code to move and add the circle, but i can call it multiple times and each one be unique without writing code to anticipate an infinite amount of circles. Here is my code:
obn = 0
ellipsex = 50
ellipsey = 50
ellipsew = 50
ellipseh = 50
ellipser = 255
ellipseg = 0
ellipseb = 0
function love.draw()
mousex, mousey = love.mouse.getPosition()
for i=0,obn,1 do
ellipse()
end
end
function love.mousereleased(x, y, button)
if button == 2 then
obn = obn + 1
end
end
function love.update(dt)
if love.mouse.isDown(1) then
if mousex > ellipsex and mousex < ellipsex + ellipsew and mousey > ellipsey and mousey < ellipsey + ellipseh then
ellipsex = mousex
ellipsey = mousey
end
end
end
function ellipse()
love.graphics.setColor(ellipser, ellipseg, ellipseb)
love.graphics.ellipse("fill", ellipsex, ellipsey, ellipsew, ellipseh)
end
But when i right-click to add a circle(increment how many times the for-loop runs) it doesnt add a second circle for me to move independent from the first one. Help?
The way I would go about handling multiple instances of ellipses is creating a table for every ellipse that would hold it's properties and a draw function.
local ellipses = {} -- store all ellipses into a table
function create_ellipse(x,y,w,h,r,g,b)
local ellipse = {
x = x,
y = y,
w = w,
h = h,
r = r,
g = g,
b = b
}
function ellipse.draw()
love.graphics.setColor(ellipse.r,ellipse.g,ellipse.b)
love.graphics.ellipse("fill",ellipse.x,ellipse.y,ellipse.w,ellipse.h)
end
ellipses[#ellipses+1] = ellipse -- insert new ellipse into ellipses table
return ellipse
end
function love.draw()
for i = 1,#ellipses do
ellipses[i].draw(); -- call each ellipse's separate draw function
end
end
function love.mousereleased(x,y,button)
if button == 2 then
create_ellipse(x,y,50,50,255,0,0) -- bonus: every ellipse is created where the user clicked
end
end
function love.update(dt)
if love.mouse.isDown(1) then
local mousex,mousey = love.mouse.getPosition() -- there is no need to request the mouse position every frame, but only when a user clicks anywhere on the screen
for i = 1,#ellipses do
local current_ellipse = ellipses[i]
if mousex >= current_ellipse.x and mousex <= current_ellipse.x+current_ellipse.w and mousey >= current_ellipse.y and mousey <= current_ellipse.y+current_ellipse.h then
current_ellipse.x = mousex
current_ellipse.y = mousey
end
end
end
end
You could even make your own Ellipse class if you're into OOP.

Balloon game with Corona SDK

I am totally new to game development for iPhone/iPad.
I have got my code working and all the 10 balloons are floating in the air but I have a few questions:
The balloons should be in the sequence or random order. They move the tendon to the edge and then the player should move back the balloons to the right place with the mouse. How?
What are the right dimensional numbers (x, y) so my balloons are equally displayed and positioned on the screen?
My random function keeps popping out more balloons by simple click.
I would like the user to perform some math operations, for instance add two random balloons and display the right answer on the screen so the result can move back to the right edge of balloon placement. how to code this? How can I use 2 different level of difficulties? (L1, L2)
How to make my balloons to move to the different edges on the screen?
How can a user move back the balloons with mouse to the right places?
How can I tie my balloons to a rope (horizontally)? so the user can make a choice.
My background image is about 3MB original(1024 x 768) to match well with iPad resolution, can I change the size without affecting the display in iPad?
I feel like the local balloon1, 2, 3, is repeated too much, and same goes to moveBalloon and applyLinear. Is there a way of shortening them? or is it normal since there are 10 balloons?
I have added sound to the first balloon by simple click, should duplicate the same function for the rest of the 9 balloons (another mess)? I will use the same sound to all.
Your feedback is much appreciated.
If you want multiple balloons, it would be MUCH MUCH easier to use a table. You can have as many baloons as you want with very little effort.
Balloons = {} -- track all baloons
Function addBalloon(x,y,xVel,yVel)
Tab = {x = x, y = y, vel = {x = xVel, y = yVel}}
Table.insert(balloons,tab)
End
Function moveAllBalloons()
For_,i in pairs(balloons) do
i.x = i.x + i.vel.x
i.y = i.y + i.vel.y
End
End
Function isPlaying
For _,i in pairs(balloons)
If --[[mouse.x]] <= i.x - (balloon.width/2) and --[[other parameters here]] then
PlaySound
End
End
End
for different difficulties, you can do something like
if L1 then
Num1 = math.random(3,15)
Num2 = math.random(3,15
OpFind = math.random(3)
If opfind == 1 then
Operation = "+"
Elseif opfind == 2 then
Operation = "-"
Elseif opfind ==3 then
Operation = "*"
End
ElseIf L2 then
num1 = math.random(7,50)
Num2 = math.random(7,50)
OpFind = math.random(4)
If opfind == 1 then
Operation = "^"
Elseif opfind == 2 then
Operation = "%"
Elseif opfind ==3 then
Operation = "*"
Elseif opfind == 4 then
Operation == "/"
End
End

Resources