Getting character to jump - coronasdk

I've created a sprite sheet(of a frog jumping) using texture packer and I am trying to get the character to jump forward when I click on the sprite. I've created an event listener and when I click on the sprite the play() method animates the sprite. But I can't get the sprite to jump forward using the applyForce or setLinearVelocity methods? Here is my code:
require("physics")
local sprite = require "sprite"
local sheetData = require "myFrogs" -- name of file created using texturepacker
physics.start()
physics.setGravity(0,1)
local _w = display.contentWidth/2
local _h = display.contentHeight/2
local spriteData = sheetData.getSpriteSheetData()
local spriteSheet = sprite.newSpriteSheetFromData("images/myFrogs.png", spriteData)
local spriteSet = sprite.newSpriteSet(spriteSheet, 1, 7) number of images in spritesheet
local frogSprite = sprite.newSprite(spriteSet)
frogSprite.x = _w
frogSprite.y = _h
physics.addBody(frogSprite, "static", {friction=1.0,density=1.0,bounce=0.3, radius=35})
frogSprite.isFixedRotation = true
local function frogJump(event)
if(event.phase == "ended") then
--frogSprite:applyForce() -- should I use this method
--frogSprite:setLinearVelocity() -- or this method
frogSprite:play()
end
end
frogSprite:addEventListener("touch", frogJump)

You made the frog's body static - switch to dynamic and it will jump using either of those methods.

By making frog body static, it will not be affected by impulse or force so it should be Dynamics
Body:applyForce( xForce, yForce, bodyX, bodyY ) <- Apply Force to your center of mass i.e Reference point you have set.
Body:setLinearVelocity( xVelocity, yVelocity ) <- It will give a velocity of data to will provide in terms of pixel per second.

Related

Physics Bug in Corona Sdk

I have a problem in Corona SDK. The physics are screwed up. Objects move in random directions
-----------------------------------------------------------------------------------------
--
-- main.lua
--
-----------------------------------------------------------------------------------------
-- Your code here
local physics_engine = require("physics")
physics_engine.start()
local background=display.newGroup()
local main_area=display.newGroup()
local sheetOptions =
{--animated sheet options
width = 389,
height = 391,
numFrames = 10
}
--load animated image sheet
local cute_charac_sheet = graphics.newImageSheet( "spritesheet.png", sheetOptions )
local sequences_cute_charac = {
-- consecutive frames sequence
{--animation options for blinking
name = "normalRun",
start = 1,
count = 10,
time=800,
loopCount = 0,
loopDirection = "bounce"
}
}
local function woodmaker(event)
local wood =display.newImageRect(main_area,'wood.png',15,45)
wood.x=event.x
wood.y=event.y
physics_engine.addBody(wood,'kinematic')
end
local cute_charac = display.newSprite( cute_charac_sheet,sequences_cute_charac)
main_area:insert(cute_charac)
cute_charac.x=display.contentCenterX
cute_charac.y=192.55
cute_charac:scale(0.1,0.1)
cute_charac:play()
local back_png= display.newImageRect(background,"Day_Back.png",480,270)
back_png.x=display.contentCenterX
back_png.y=display.contentCenterY
back_png:addEventListener( "tap", woodmaker )
local ground_grass=display.newImageRect(main_area,"grass.png",480,60)
ground_grass.x=display.contentCenterX
ground_grass.y=240
local grass_texture=display.newImageRect(main_area,'grassup.png',480,5)
grass_texture.x=display.contentCenterX
grass_texture.y=210
physics_engine.addBody(cute_charac,"dynamic")
physics_engine.addBody(grass_texture,'static',{bounce=0,})
Also removing the ground_grass fixes it.Why is this happening
Also making the wood dynamic pushes it towards the sides and if the wood is placed in the middle it moves down.

One by one addEventListener collision

I'm working on a simple breakout game and I've problem with ball:addEventListener( "collision", removeBricks ), it works fine until the ball hits two bricks at same time, than the up/down direction (vy) switch twice, making the ball continue moving up or down.
How can do one by one addEventListener collision and disable multiple collides at once?
function removeBricks(event)
if event.other.isBrick == 1 then
vy = vy * (-1)
...
end
end
Instead of changing ball's velocity in the removeBricks function, you can just flip a flag that means "a ball has hit some bricks and should change it's direction", and then in your enterFrame handler just change the ball's speed:
local ballHasCollided = false
local function removeBricks(event)
if event.other.isBrick == 1 then
ballHasCollided = true
end
end
local function updateBallVelocity(event)
if ballHasCollided then
ballHasCollided = false
ball.vy = -ball.vy
-- ...
end
-- your game set up code somewhere
Runtime:addEventListener('enterFrame', updateBallVelocity)

Corona "Attempt to remove an object that has already been removed"

I'm working on a simple "breakout" game and I have problem reloading a map.
for example: if I start with level1, break some bricks and lose, than I'm loading the same map again. next time that the ball collides with the same brick I "touched" before, will give me an error Attempt to remove an object that has already been removed
local map = lime.loadMap("maps/" .. currentLevel .. ".tmx")
local layer = map:getTileLayer("bricks_1")
local visual = lime.createVisual(map)
local physical = lime.buildPhysical(map)
function removeBricks(event)
if event.other.isBrick then
local brick = event.other
transition.to(brick, {time = 20, alpha = 0})
score = score + brick.scoreValue
ScoreNum.text = score
-- remove brick
brick:removeSelf()
brick = nil
...
i think the second time you go to your game the event.other is not created are you using storyboard if so you can try to remove the scene after the game is over so when you go to your game again it will recreate all the object
Have you try this?
transition.to(brick, {time = 20, alpha = 0, onComplete = function()
if brick then
brick:removeSelf()
brick = nil
end
end})
If you are using physics you also have to do a physics.removeBody(brick) before you remove the object itself so that it detaches from the physics engine. If not physics thinks it's still there.

Corona SDK adding physics bodies/ not accepting collisions

I am attempting to add/remove objects from the physics engine (addBody() and removeBody()) in an app I am working on. The app I am working on is modular so the issue is in one of two files.
The objects file (TransmitterObject) or the main file (main):
This is the relevant code for both:
main.lua
local physics = require("physics")
physics.start()
physics.setGravity(0,0)
physics.setDrawMode( "debug" )
local TransmitterObject = require("TransmitterObject")
function updateGame(event)
if(ITERATIONS % 100 == 0) then
tran1:activate() --create new physics object here
end
ITERATIONS = ITERATIONS + 1
--print(ITERATIONS)
end
Runtime:addEventListener("enterFrame", updateGame)
TransmitterObject.lua
function transmitter.new(props) --constructor
Transmitter =
{
x = props.x,
y = props.y,
receivers = props.receivers
}
return setmetatable( Transmitter, transmitter_mt )
end
function transmitter:activate()
local group = math.random(1, #self.receivers)
local receiver = math.random(1,#self.receivers[group])
local x , y = self.receivers[group][receiver][1], self.receivers[group][receiver][2]
local d = math.sqrt(math.pow((self.x-x),2) + math.pow((self.y-y),2))
local dx = math.abs(self.x - x)
local angle = math.deg(math.acos(dx/d))
local beam = display.newRect(self.x,self.y, d, 10)
beam:setReferencePoint(display.TopLeftReferencePoint)
beam.rotation = 180 + angle
beam:setFillColor(0,255,0)
beam.alpha = 0
local function add(event)
physics.addBody(beam, "static")
end
local function delete(event)
physics.removeBody(beam)
end
transition.to( beam, { time=1000, alpha=1.0, onComplete=add } )
transition.to( beam, { time=1000, delay=2500, alpha=0, onComplete=delete})
end
Now let me try to describe the issue a little better. basically every 100th time that 'enterFrame' fires I tell the transmitter object (tran1) to call its function 'activate'
which then preforms some basic math to get coordinates. Then it creates a rectangle (beam) using the calculated information and sets some properties. That is all basic stuff. Next I tell it to transition from not visible (alpha = 0) to visible over the span of 1 second. When does it is to call the function 'add' which adds the object to the physics engine. Likewise with the next line where it removes the objects.
That being said, when i set physics.setDrawMode( "debug" ) the beam object appears as a static body, but does not accept collisions. Does anyone know why the above code would not accept collisions for the beam object?
Keep in mind I have other objects that do work properly within the physics engine.
Wow, I'm answering super late!
On collisions, modifying bodies aren't supported.
What I propose you is to create a new function,
local function addBody ( event )
physics.addBody(ball, "static")
end
and in your collision event you have to add this,
timer.performWithDelay(500, addBody)
The only thing that may cause some problems it's the delay, but as the collision doesn't take too much time it should be ok.
Sorry for this necroposting,
It's just to help other people that may have that problem,
Fannick

In Corona SDK the background image always cover other images

I'm currently making a tower defense game with Corona SDK. However, while I'm making the gaming scene, The background scene always cover the monster spawn, I've tried background:toBack() ,however it's doesn't work.Here is my code:
module(..., package.seeall)
function new()
local localGroup = display.newGroup();
local level=require(data.levelSelected);
local currentDes = 1;
monsters_list = display.newGroup()
--The background
local bg = display.newImage ("image/levels/1/bg.png");
bg.x = _W/2;bg.y = _H/2;
bg:toBack();
--generate the monsters
function spawn_monster(kind)
local monster=require("monsters."..kind);
newMonster=monster.new()
--read the spawn(starting point) in level, and spawn the monster there
newMonster.x=level.route[1][1];newMonster.y=level.route[1][2];
monsters_list:insert(newMonster);
localGroup:insert(monsters_list);
return monsters_list;
end
function move(monster,x,y)
-- Using pythagoras to calauate the moving distace, Hence calauate the time consumed according to speed
transition.to(monster,{time=math.sqrt(math.abs(monster.x-x)^2+math.abs(monster.y-y)^2)/(monster.speed/30),x=x, y=y, onComplete=newDes})
end
function newDes()
currentDes=currentDes+1;
end
--moake monster move according to the route
function move_monster()
for i=1,monsters_list.numChildren do
move(monsters_list[i],200,200);
print (currentDes);
end
end
function agent()
spawn_monster("basic");
end
--Excute function above.
timer2 = timer.performWithDelay(1000,agent,10);
timer.performWithDelay(100,move_monster,-1);
timer.performWithDelay(10,update,-1);
move_monster();
return localGroup;
end
and the monster just stuck at the spawn point and stay there.
but, When i comment these 3 lines of code:
--local bg = display.newImage ("image/levels/1/bg.png");
--bg.x = _W/2;bg.y = _H/2;
--bg:toBack();
The problem disappear
Any ideas??Thanks for helping
Since you are using director, you should insert all your display objects into the localGroup.
You haven't inserted bg into localGroup.
SO director class inserts bg finally after inserting localGroup.
Modify your code as
--The background
local bg = display.newImage (localGroup,"image/levels/1/bg.png");
bg.x = _W/2;bg.y = _H/2;
bg:toBack();
or add the code
localGroup:insert(bg)
In more recent versions of Corona SDK:
Composer is the official scene (screen) creation and management library in Corona SDK.... The primary object in the Composer library is the scene object...and it contains a unique self.view.... This self.view is where you should insert visual elements pertaining to the scene.
So now in your scene:create() method, you should insert all DisplayObjects into self.view. It looks like this:
local composer = require( "composer" )
local scene = composer.newScene()
function scene:create()
local sceneGroup = self.view
local bg = display.newImage( ...
bg.x, bg.y = ...
local dude = display.newImage( ...
dude.x, dude.y = ....
sceneGroup:insert(bg)
sceneGroup:insert(dude)
end
The layering of DisplayObjects in this sceneGroup depends on the order in which they are added to the group, with the object added last on top. You can control this ordering with the toBack() and toFront() methods.

Resources