Anyone can help me. I create some sprite images for a jump animate. But it cannot animated as I want, it only showing the first frame ( I set it for 7 jump frame). Here is my corona code.
function playerJump( event )
if event.phase == "ended" then
if doubleJump == false then
player:setLinearVelocity( 0, 0 )
player:applyForce(0,-30, player.x, player.y)
player:setSequence("jump")
jumpChannel = audio.play(jumpSound)
end
if singleJump == false then singleJump = true
else doubleJump = true end
end
return true
end
Then below that function, I generate the sprite
local options =
{
width = 60, height = 100,
numFrames = 33,
sheetContentWidth = 1980,
sheetContentHeight = 100
}
playerSheet = graphics.newImageSheet( "images/playerSprite.png", options)
playerSprite = {
{name="run", frames = {1,3,5,7,9,11,13,15,17,19,21,23,25}, time = 700, loopCount = 0 },
{name="jump", frames = {27,28,29,30,31,32,33}, time = 1000, loopCount = 1 },
}
--Add the jump listener
Runtime:addEventListener("touch", playerJump)
Thankyou very much
Regards
function playerJump( event )
if event.phase == "ended" then
if doubleJump == false then
player:setLinearVelocity( 0, 0 )
player:applyForce(0,-30, player.x, player.y)
player:setSequence("jump")
player:play() --- You have forgot to add this line.
jumpChannel = audio.play(jumpSound)
end
if singleJump == false then singleJump = true
else doubleJump = true end
end
return true
end
Related
I have recently been familiar with lua in LOVE 2D and watched some tutorials and now am trying to make a simple game. The game will feature a character who can run and when pressed 'space', attack(strike with his sword). When pressed 'space', it should go through all the frames/sprites of attacking animation. But the character is not going through all the frames and the interval between them seems really fast even though I kept it minimum.
This is the code I am using to account for the key pressing.
self.animations = {
['idle'] = Animation{
frames = {
self.frames[1]
},
interval = 1
},
['attack'] = Animation{
frames = {
self.frames[1], self.frames[2], self.frames[3], self.frames[4], self.frames[5], self.frames[6], self.frames[3]
},
interval = 0.25
}
}
self.animation = self.animations['idle']
self.currentFrame = self.animation:getCurrentFrame()
self.behaviors = {
['idle'] = function(dt)
if love.keyboard.wasPressed('space') then
self.dy = 0
self.state = 'attack'
self.animation = self.animations['attack']
elseif love.keyboard.wasPressed('up') then
self.dy = -MOVE_DIST
elseif love.keyboard.wasPressed('down') then
self.dy = MOVE_DIST
else
self.dy = 0
end
end,
['attack'] = function(dt)
self.animation = self.animations['attack']
if love.keyboard.wasPressed('up') then
self.dy = -MOVE_DIST
elseif love.keyboard.wasPressed('down') then
self.dy = MOVE_DIST
else
self.dy = 0
self.state = 'idle'
self.animation = self.animations['idle']
end
end
This is my animation class that's responsible for transition effects
Animation = Class{}
function Animation:init(params)
--self.texture = params.texture
self.frames = params.frames
self.interval = params.interval or 0.05
self.timer = 0
self.currentFrame = 1
end
function Animation:getCurrentFrame()
return self.frames[self.currentFrame]
end
function Animation:restart()
self.timer = 0
self.currentFrame = 1
end
function Animation:update(dt)
self.timer = self.timer + dt
if #self.frames == 1 then
return self.currentFrame
else
while self.timer > self.interval do
self.timer = self.timer - self.interval
self.currentFrame = (self.currentFrame + 1) % (#self.frames + 1)
if self.currentFrame == 0 then
self.currentFrame = 1
end
end
end
end
Please help. I hope I asked the question correctly. Thanks in advance.
Don't really know how you deal with the state in the key pressing code but this could be part of the issue too.
Anyway, your Animation:update looks very weird to me and I really think this is the center of the problem. There is a simple function that you could use instead and it should work perfectly (if you have any question about it feel free to ask).
If your not really comfortable with a debugger you could use love.graphics.print to print some value to the screen (like self.currentFrame or self.timer in that case) to see what's going on with those value in real time.
function Animation:update(dt)
self.timer = self.timer + dt/self.interval
if self.timer >= #self.frames then
self.timer = 0
end
self.currentFrame = Math.floor(self.timer)+1
end
Also note that "Math.floor(self.timer)+1" cannot be replaced by "Math.ceil(self.timer)" because it will return 0 if self.timer == 0 (and lua's array starts at one)
Edit:
It could probably come from here:
['attack'] = function(dt)
self.animation = self.animations['attack']
if love.keyboard.wasPressed('up') then
self.dy = -MOVE_DIST
elseif love.keyboard.wasPressed('down') then
self.dy = MOVE_DIST
else
self.dy = 0
self.state = 'idle'
self.animation = self.animations['idle']
end
end
I don't know how you deal with your inputs since 'love.keyboard.wasPressed' if not a love function but if 'up' and 'down' where not pressed the last frame, the state will go back to 'idle' and the animation to animations['idle']
Without more code I cannot do much more for you.
Iam new to corona, so I dont know how to organize my code to best. I am trying to regiser click when user click on leftHam image, but I dont how to do it most efficently. Right now I am getting leftHam is nil although on creation it should be assinged a value.
local composer = require( "composer" )
local widget = require( "widget" )
local scene = composer.newScene()
local _H = display.contentHeight
local _W = display.contentWidth
leftNavBtn = nil
local navbarGroup
function scene:create( event )
local sceneGroup = self.view
local background = display.newImage("res/bg.png" )
background:scale( _W, _H )
background.x = _W
background.y = _H
local navbarGroup = display.newContainer(_W, _H/4)
navbarGroup.x = _W /2
--navbarGroup.y = 0
local top_bar = display.newImage("res/home/top_bar.png")
top_bar.y = top_bar.height/2
navbarGroup:insert(top_bar)
--local leftNavBtn = display.newImageRect("res/home/hamburger.png", 100, 100)
leftNavBtn.y = leftNavBtn.height/1.5
leftNavBtn.x = - navbarGroup.width/2 + leftNavBtn.width
leftNavBtn = display.newImageRect("res/home/hamburger.png", 100, 100)
leftNavBtn.y = leftNavBtn.height/1.5
leftNavBtn.x = - navbarGroup.width/2 + leftNavBtn.width
navbarGroup:insert(leftNavBtn)
local rightNavBtn = display.newImageRect("res/home/hamburger.png", 100, 100)
rightNavBtn.y = leftNavBtn.height/1.5
rightNavBtn.x = navbarGroup.width/2 - leftNavBtn.width
navbarGroup:insert(rightNavBtn)
end
function test()
print("clickedddddddddddd")
end
function leftNavBtn:touch(event)
if event.phase == "began" then
display.getCurrentStage( ):setFocus(self)
self.isFocus = true
elseif self.isFocus then
if event.phase == "moved" then
print("moved")
elseif event.phase == "ended" or event.phase == "cancelled" then
display.getCurrentStage( ):setFocus(nil)
self.isFocus = false
end
end
return true
end
leftNavBtn:addEventListener( "touch", test )
scene:addEventListener( "create", scene )
return scene
Do you mean leftNavBtn because leftHam doesn't exist anywhere.
You are creating leftNavBtn in scene:create but are attempting to use it before calling that function anywhere (the leftNavBtn:addEventListener( "touch", test )) line.
Within scene:create you also use leftNavBtn before creating it because you commented out this line local leftNavBtn = display.newImageRect("res/home/hamburger.png", 100, 100) without commenting out the two lines after it (which set of three lines you then duplicate immediately after that).
I made this game in python 2.7 and it worked in .py format but when I compiled it with py2exe it suddenly broke. It gave me this error:
"Microsoft Visuak C++ Runtime Library
Runtime Error!
Program C:\Python27\Helmetdodger\Stuffz\main.exe
This application has requested the Runtime to terminate it in an unusual way.
Please contact the program's support team."
The code:
import pygame
import random, sys, os
from pygame.locals import *
WINDOWWIDTH = 1200
WINDOWHEIGHT = 900
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0, 0, 0)
FPS = 40
BADDIEMINSIZE = 10
BADDIEMAXSIZE = 40
BADDIEMINSPEED = 1
BADDIEMAXSPEED = 8
ADDNEWBADDIERATE = 6
PLAYERMOVERATE = 5
def terminate():
pygame.quit()
os.exit(1)
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE: # pressing escape quits
terminate()
return
def playerHasHitBaddie(playerRect, baddies):
for b in baddies:
if playerRect.colliderect(b['rect']):
return True
return False
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
# set up pygame, the window, and the mouse cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Helmetdodger')
pygame.mouse.set_visible(False)
# set up fonts
font = pygame.font.SysFont(None, 48)
# set up sounds
gameOverSound = pygame.mixer.Sound('gameover.wav')
pygame.mixer.music.load('background.mid')
# set up images
playerImage1 = pygame.image.load('player1.png')
powerImage = pygame.image.load('power.png')
playerRect = playerImage1.get_rect()
baddieImage1 = pygame.image.load('baddie.png')
baddieImage2 = pygame.image.load('baddie1.png')
baddieImage3 = pygame.image.load('baddie2.png')
baddieImage4 = pygame.image.load('baddie3.png')
baddieImage5 = pygame.image.load('baddie4.png')
baddieImage6 = pygame.image.load('baddie5.png')
baddieImage7 = pygame.image.load('baddie6.png')
baddieImage8 = pygame.image.load('baddie7.png')
baddieImage9 = pygame.image.load('baddie8.png')
baddieImage10 = pygame.image.load('baddie9.png')
baddieImage11 = pygame.image.load('baddie10.png')
baddieImage12 = pygame.image.load('baddie11.png')
baddieImage13 = pygame.image.load('baddie12.png')
baddieImage14 = pygame.image.load('baddie13.png')
baddieImage15 = pygame.image.load('baddie14.png')
baddieImage16 = pygame.image.load('baddie15.png')
baddieImage17 = pygame.image.load('baddie16.png')
baddieImage18 = pygame.image.load('baddie17.png')
baddieImage19 = pygame.image.load('baddie18.png')
baddieImage20 = pygame.image.load('baddie19.png')
baddieImage21 = pygame.image.load('baddie20.png')
baddieImage22 = pygame.image.load('baddie21.png')
baddieImage23 = pygame.image.load('baddie22.png')
baddieImage24 = pygame.image.load('baddie23.png')
baddieImage25 = pygame.image.load('baddie24.png')
baddieImage26 = pygame.image.load('baddie25.png')
baddieImage27 = pygame.image.load('baddie26.png')
baddieImage28 = pygame.image.load('baddie27.png')
baddieImage29 = pygame.image.load('baddie28.png')
baddieImage30 = pygame.image.load('baddie29.png')
baddieImages = [baddieImage1, baddieImage2, baddieImage3, baddieImage4, baddieImage5, baddieImage6, baddieImage7, baddieImage8, baddieImage9, baddieImage10, baddieImage11, baddieImage12, baddieImage13, baddieImage14, baddieImage15, baddieImage16, baddieImage17, baddieImage18, baddieImage19, baddieImage20, baddieImage21, baddieImage22, baddieImage23, baddieImage24, baddieImage25, baddieImage26, baddieImage27, baddieImage28, baddieImage29, baddieImage20]
# show the "Start" screen
drawText('Helmetdodger', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to start.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
#Get highscore
topScore = 0
try:
file = open('hs.txt', "r")
topScore = file.read()
topScore = int(topScore)
file.close()
except:
topScore = 0
while True:
# set up the start of the game
baddies = []
score = 0
playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
baddieAddCounter = 0
pygame.mixer.music.play(-1, 0.0)
powerCount = 0
while True: # the game loop runs while the game part is playing
score += 1 # increase score
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == ord('z'):
reverseCheat = True
if event.key == ord('x'):
slowCheat = True
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.type == KEYUP:
if event.key == ord('z'):
reverseCheat = False
score = 0
if event.key == ord('x'):
slowCheat = False
score = 0
if event.key == K_ESCAPE:
terminate()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
if event.type == MOUSEMOTION:
# If the mouse moves, move the player where the cursor is.
playerRect.move_ip(event.pos[0] - playerRect.centerx, event.pos[1] - playerRect.centery)
# Add new baddies at the top of the screen, if needed.
if not reverseCheat and not slowCheat:
baddieAddCounter += 1
if baddieAddCounter == ADDNEWBADDIERATE:
baddieCount = random.randrange(len(baddieImages))
baddieAddCounter = 0
baddieSize = random.randint(BADDIEMINSIZE, BADDIEMAXSIZE)
newBaddie = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-baddieSize), 0 - baddieSize, baddieSize, baddieSize),
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':pygame.transform.scale(baddieImages[baddieCount], (baddieSize, baddieSize)),
}
baddies.append(newBaddie)
# Move the player around.
if moveLeft and playerRect.left > 0:
playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
if moveRight and playerRect.right < WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVERATE, 0)
if moveUp and playerRect.top > 0:
playerRect.move_ip(0, -1 * PLAYERMOVERATE)
if moveDown and playerRect.bottom < WINDOWHEIGHT:
playerRect.move_ip(0, PLAYERMOVERATE)
# Move the mouse cursor to match the player.
pygame.mouse.set_pos(playerRect.centerx, playerRect.centery)
# Move the baddies down.
for b in baddies:
if not reverseCheat and not slowCheat:
b['rect'].move_ip(0, b['speed'])
elif reverseCheat:
b['rect'].move_ip(0, -5)
elif slowCheat:
b['rect'].move_ip(0, 1)
# Delete baddies that have fallen past the bottom.
for b in baddies[:]:
if b['rect'].top > WINDOWHEIGHT:
baddies.remove(b)
# Draw the game world on the window.
windowSurface.fill(BACKGROUNDCOLOR)
# Draw the score and top score.
drawText('Score: %s' % (score), font, windowSurface, 10, 0)
drawText('Top Score: %s' % (topScore), font, windowSurface, 10, 40)
# Draw the player's rectangle
windowSurface.blit(playerImage1, playerRect)
# Draw each baddie
for b in baddies:
windowSurface.blit(b['surface'], b['rect'])
pygame.display.update()
# Check if any of the baddies have hit the player.
if playerHasHitBaddie(playerRect, baddies):
if score > topScore:
topScore = score # set new top score
file = open("hs.txt", "w")
score = str(score)
file.write(score)
file.close()
break
mainClock.tick(FPS)
# Stop the game and show the "Game Over" screen.
pygame.mixer.music.stop()
gameOverSound.play()
drawText('GAME OVER', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
gameOverSound.stop()
My buildscript was incorrect, I found a better buildscript online to use instead
try:
from distutils.core import setup
import py2exe, pygame
from modulefinder import Module
import glob, fnmatch
import sys, os, shutil
import operator
except ImportError, message:
raise SystemExit, "Unable to load module. %s" % message
#hack which fixes the pygame mixer and pygame font
origIsSystemDLL = py2exe.build_exe.isSystemDLL # save the orginal before we edit it
def isSystemDLL(pathname):
# checks if the freetype and ogg dll files are being included
if os.path.basename(pathname).lower() in ("libfreetype-6.dll", "libogg-0.dll","sdl_ttf.dll"): # "sdl_ttf.dll" added by arit.
return 0
return origIsSystemDLL(pathname) # return the orginal function
py2exe.build_exe.isSystemDLL = isSystemDLL # override the default function with this one
class pygame2exe(py2exe.build_exe.py2exe): #This hack make sure that pygame default font is copied: no need to modify code for specifying default font
def copy_extensions(self, extensions):
#Get pygame default font
pygamedir = os.path.split(pygame.base.__file__)[0]
pygame_default_font = os.path.join(pygamedir, pygame.font.get_default_font())
#Add font to list of extension to be copied
extensions.append(Module("pygame.font", pygame_default_font))
py2exe.build_exe.py2exe.copy_extensions(self, extensions)
class BuildExe:
def __init__(self):
#Name of starting + .py
self.script = "raw.py"
#Name of program
self.project_name = "main"
#Project url
self.project_url = "about:none"
#Version of program
self.project_version = "0.0"
#License of the program
self.license = "MyApps License"
#Auhor of program
self.author_name = "Me"
self.author_email = "example#example.com"
self.copyright = "Copyright (c) 2009 Me."
#Description
self.project_description = "MyApps Description"
#Icon file (None will use pygame default icon)
self.icon_file = None
#Extra files/dirs copied to game
self.extra_datas = []
#Extra/excludes python modules
self.extra_modules = []
self.exclude_modules = []
#DLL Excludes
self.exclude_dll = ['']
#python scripts (strings) to be included, seperated by a comma
self.extra_scripts = []
#Zip file name (None will bundle files in exe instead of zip file)
self.zipfile_name = None
#Dist directory
self.dist_dir ='C:\Python27\dist'
## Code from DistUtils tutorial at http://wiki.python.org/moin/Distutils/Tutorial
## Originally borrowed from wxPython's setup and config files
def opj(self, *args):
path = os.path.join(*args)
return os.path.normpath(path)
def find_data_files(self, srcdir, *wildcards, **kw):
# get a list of all files under the srcdir matching wildcards,
# returned in a format to be used for install_data
def walk_helper(arg, dirname, files):
if '.svn' in dirname:
return
names = []
lst, wildcards = arg
for wc in wildcards:
wc_name = self.opj(dirname, wc)
for f in files:
filename = self.opj(dirname, f)
if fnmatch.fnmatch(filename, wc_name) and not os.path.isdir(filename):
names.append(filename)
if names:
lst.append( (dirname, names ) )
file_list = []
recursive = kw.get('recursive', True)
if recursive:
os.path.walk(srcdir, walk_helper, (file_list, wildcards))
else:
walk_helper((file_list, wildcards),
srcdir,
[os.path.basename(f) for f in glob.glob(self.opj(srcdir, '*'))])
return file_list
def run(self):
if os.path.isdir(self.dist_dir): #Erase previous destination dir
shutil.rmtree(self.dist_dir)
#Use the default pygame icon, if none given
if self.icon_file == None:
path = os.path.split(pygame.__file__)[0]
self.icon_file = os.path.join(path, 'pygame.ico')
#List all data files to add
extra_datas = []
for data in self.extra_datas:
if os.path.isdir(data):
extra_datas.extend(self.find_data_files(data, '*'))
else:
extra_datas.append(('.', [data]))
setup(
cmdclass = {'py2exe': pygame2exe},
version = self.project_version,
description = self.project_description,
name = self.project_name,
url = self.project_url,
author = self.author_name,
author_email = self.author_email,
license = self.license,
# targets to build
windows = [{
'script': self.script,
'icon_resources': [(0, self.icon_file)],
'copyright': self.copyright
}],
options = {'py2exe': {'optimize': 2, 'bundle_files': 2, 'compressed': True, \
'excludes': self.exclude_modules, 'packages': self.extra_modules, \
'dll_excludes': self.exclude_dll,
'includes': self.extra_scripts} },
zipfile = self.zipfile_name,
data_files = extra_datas,
dist_dir = self.dist_dir
)
if os.path.isdir('build'): #Clean up build dir
shutil.rmtree('build')
if __name__ == '__main__':
if operator.lt(len(sys.argv), 2):
sys.argv.append('py2exe')
BuildExe().run() #Run generation
raw_input("Press any key to continue") #Pause to let user see that things ends
I have a event listener assigned to an object. This then triggers the startDrag function. I'm moving my character in the game with dragging. But as soon as I scroll or move the display, my dragging function gets all messed up. It doesn't react as it should and the object(event.target) can't be controlled at all.
Did anyone else had this experience?
Is this a corona bug?
How can I solve this?
Can I temporarily disable the startDrag event listener for the time of scrolling? Or maybe restart it?
All help would be greatly appreciated.
Here is the code...
local physics = require( "physics" )
physics.start()
physics.setContinuous( false )
display.setStatusBar( display.HiddenStatusBar )
physics.setScale( 60 )
physics.setDrawMode( "hybrid" )
local height = display.contentHeight
local width = display.contentWidth
local allElements = display.newGroup()
local texsGroup = display.newGroup()
local backGround = display.newRect(0,0-height,width,2*height)
backGround:setFillColor(91,91,91)
backGround:toBack()
local wallBottom = display.newRect(texsGroup, 0,height-20,width,20)
physics.addBody(wallBottom, "static", { density=5, friction=0.5, bounce=0.3 } )
local tex = {}
local numberRips = 60
local texSize = {
-- w: texwidth, h: texheight, s: strength required
{w=30, h=20, s=1},
{w=20, h=10, s=1.5},
{w=10, h=10, s=2},
}
local r
local lim = display.newGroup()
local function createRips()
local originX = 0
local originY = height -75
for i=0,numberRips do
r = math.random(3)
local x = originX + math.random(width)
local y = originY - math.random(2*height)
tex[i] = display.newRect(lim, x, y, texSize[r].w, texSize[r].h)
tex[i].status = "active"
tex[i].size = texSize[r].s
if (r == 1) then
tex[i]:setFillColor(51,255,0)
elseif (r == 2) then
tex[i]:setFillColor(255,51,51)
elseif (r == 3) then
tex[i]:setFillColor(51,51,255)
end
end
end
createRips()
local w, h, r = width/2, height - 265, 12
local L = display.newCircle(w-115,h+29,r)
local buttonRadius = 35
local button3 = display.newCircle((L.x),(L.y),buttonRadius)
button3.myName = "L"
allElements:insert(button3)
allElements:insert(lim)
allElements:insert(L)
local d, f, b = 15, 1, 0.15
physics.addBody(L, "dynamic", { density=d, friction=f, bounce=b, radius=r } )
button3.isVisible = false
button3.isHitTestable = true
physics.addBody( button3, "static", { density=1, radius=buttonRadius } )
local function addFrictionJoint(a, b, posX, posY, lowerAngle, upperAngle, mT)
local j = physics.newJoint ( "pivot", a, b, posX, posY, rFrom, rTo)
j.isLimitEnabled = true
j:setRotationLimits (lowerAngle, upperAngle)
return j
end
-- JOINTS
addFrictionJoint( button3, L, L.x, L.y, 0, 0 )
local function startDrag( event, params )
local body = event.target
local phase = event.phase
local stage = display.getCurrentStage()
local direction = event.direction
if "began" == phase then
stage:setFocus( body, event.id )
body.isFocus = true
event.target.bodyType = "dynamic"
-- Create a temporary touch joint and store it in the object for later reference
if params and params.center then
-- drag the body from its center point
body.tempJoint = physics.newJoint( "touch", body, body.x, body.y )
else
-- drag the body from the point where it was touched
body.tempJoint = physics.newJoint( "touch", body, event.x, event.y )
end
--body.tempJoint.maxForce = 0.25*body.tempJoint.maxForce
-- Apply optional joint parameters
if params then
local maxForce, frequency, dampingRatio
if params.maxForce then
-- Internal default is (1000 * mass), so set this fairly high if setting manually
body.tempJoint.maxForce = params.maxForce
end
if params.frequency then
-- This is the response speed of the elastic joint: higher numbers = less lag/bounce
body.tempJoint.frequency = params.frequency
end
if params.dampingRatio then
-- Possible values: 0 (no damping) to 1.0 (critical damping)
body.tempJoint.dampingRatio = params.dampingRatio
end
end
elseif body.isFocus then
if "moved" == phase then
-- Update the joint to track the touch
body.tempJoint:setTarget( event.x, event.y )
elseif "ended" == phase or "cancelled" == phase then
stage:setFocus( body, nil )
body.isFocus = false
-- Remove the joint when the touch ends
body.tempJoint:removeSelf()
body.bodyType = "static"
end
end
-- Stop further propagation of touch event
return true
end
function moveCamera(e)
if button3.y < -lim.y + 300 then
allElements.y = -(button3.y - 300)
end
end
Runtime:addEventListener("enterFrame", moveCamera)
button3:addEventListener( "touch", startDrag )
When you scroll the screen the touch event and the physics object are in different coordinate systems. See localToContent/globalToContent
I have touch problem with dynamic image creation. my code is
local widget = require "widget"
--Hide status bar
display.setStatusBar( display.HiddenStatusBar )
--bg image
local backgroundPortrait = display.newImage( "background.png", 0, 0 )
--local image1Group
--image1Group = display.newGroup()
--3 frames
local frame1 = display.newImageRect( "icon_1.png", 75, 75 )
frame1:setReferencePoint( display.CenterReferencePoint )
frame1.x = 160
frame1.y = 120
local frame2 = display.newImageRect( "icon_2.png", 75, 75 )
frame2:setReferencePoint( display.CenterReferencePoint )
frame2.x = 60
frame2.y = 360
local frame3 = display.newImageRect( "icon_3.png", 75, 75 )
frame3:setReferencePoint( display.CenterReferencePoint )
frame3.x = 260
frame3.y = 360
-- Center image
function createImage()
centerFrame = display.newImageRect( "additionalvampire1.jpg", 75, 75 )
centerFrame:setReferencePoint( display.CenterReferencePoint )
centerFrame.x = display.contentCenterX
centerFrame.y = display.contentCenterY
centerFrame:addEventListener("touch", centerFrame)
end
createImage()
function removeTouchEventFun()
centerFrame:removeEventListener("touch", centerFrame)
end
function transitionCompleted(centerFrame)
print("transitionCompleted called")
removeTouchEventFun()
centerFrame:removeSelf()
centerFrame=nil
createImage()
end
function centerFrame:touch(event)
if event.phase == "began" then
self.markX = self.x -- store x location of object
self.markY = self.y -- store y location of object
elseif event.phase == "moved" then
local x = (event.x - event.xStart) + self.markX
local y = (event.y - event.yStart) + self.markY
self.x, self.y = x, y -- move object based on calculations above
elseif event.phase == "ended" then
if (centerFrame.x<=160 and centerFrame.y>=240) then
transition.to( centerFrame, { time=1000, alpha=1, x=60, y=360, width=1 ,height=1, onComplete= transitionCompleted } )
elseif (centerFrame.x>=160 and centerFrame.y>=240) then
transition.to( centerFrame, { time=1000, alpha=1, x=260, y=360, width=1 ,height=1, onComplete= transitionCompleted } )
else
transition.to( centerFrame, { time=1000, alpha=1, x=160, y=120, width=1 ,height=1, onComplete= transitionCompleted } )
end
end
return true
end
when drag the image to any one frame it is zoom-out and remove the object and create the another image. for this image touch not working...
i need image creation with touch action when the image transition compete method. what should i do?...
local centerFrame
function transitionCompleted(centerFrame)
print("transitionCompleted called")
if(centerFrame) then
centerFrame:removeSelf()
centerFrame=nil
createImage()
end
end
function onCenterFrameTouch(event)
//your code here
end
function createImage()
centerFrame = display.newImageRect( "additionalvampire1.jpg", 75, 75 )
centerFrame:setReferencePoint( display.CenterReferencePoint )
centerFrame.x = display.contentCenterX
centerFrame.y = display.contentCenterY
centerFrame:addEventListener("touch", onCenterFrameTouch)
end