Quick Links: Download Gideros Studio | Gideros Documentation | Gideros community chat | DONATE
Make a sprite move left or right when swiped — Gideros Forum

Make a sprite move left or right when swiped

Tom2012Tom2012 Guru
edited December 2012 in Code snippets
Here's the code I used for this in my game Hungry Hector. In case it helps anyone - here's the code.

As always - any improvements welcomed.

In main.lua.
-- setup the sprite / swipe movement
 
local heroSprite = SwipeSprite.new()
stage:addChild(heroSprite)
And here's the class file
SwipeSprite = Core.class(Sprite);
 
 
function SwipeSprite:init()
 
-- Set up sprite
 
local mySprite = Bitmap.new(Texture.new("block.png"));
self:addChild(mySprite)
 
self.swipeTime = 0;
 
-- set up swipe timer
 
local timer = Timer.new(100, math.huge);
self.swipeTimer = timer;
timer:addEventListener(Event.TIMER, self.timeSwipe, self);
 
self.speed = 2.3;
 
-- touch listeners
 
self:addEventListener(Event.TOUCHES_BEGIN, self.touchesBegin, self);
self:addEventListener(Event.TOUCHES_END, self.touchesEnd, self);
self:addEventListener(Event.ENTER_FRAME, self.onEnterFrame, self);
 
end
 
-- Enterframe loop - animation etc
 
function SwipeSprite:onEnterFrame()
 
if(self.moving=="right") then
	self:setX(self:getX()+self.speed)
elseif(self.moving=="left") then
	self:setX(self:getX()-self.speed)
end
 
end
 
 
function SwipeSprite:timeSwipe()
	self.swipeTime = self.swipeTime + 100;
end
 
 
-- When touch begins
function SwipeSprite:touchesBegin(event)
 
		self.alreadySwiping = true -- ignore any touches that happen while we are swiping
		self.activeTouchId = event.touch.id -- remember touch id
		self.startX = event.touch.x;
		self.swipeTimer:start();
 
end
 
 
function SwipeSprite:touchesEnd(event)
 
		if(self.activeTouchId == event.touch.id) then -- if this is the touch that started the swipe
 
			self.swipeTimer:stop();
			self.swipeTime = 0;
 
			self.alreadySwiping = false
 
			if(self.swipeTime <= 800) then
				if(event.touch.x > self.startX + 20) then
					self.moving = "right";
 
				elseif(event.touch.x < self.startX - 20) then
					self.moving = "left"
 
				end
 
			end
		end
 
end
I've attached an example game project below. Hope it helps. ;-)

Likes: TsubasaOzora

+1 -1 (+1 / -0 )Share on Facebook

Comments

Sign In or Register to comment.