Quick Links: Download Gideros Studio | Gideros Documentation | Gideros Development Center | Gideros community chat | DONATE
Make a character move to a mouse or touch then stop — Gideros Forum

Make a character move to a mouse or touch then stop

Tom2012Tom2012 Guru
edited November 2012 in Code snippets
Thought this might be helpful for some folks here...

Code to make a sprite follow each touch or click you make.

Please post any improvements or things I've got wrong... :-)
-- Add hero
 
local hero = Bitmap.new(Texture.new("gfx/happy-block.png"))
hero:setAnchorPoint(.5,.5)
stage:addChild(hero)
hero:setPosition(100,100)
 
local move = 3; -- pixels moved each frame
 
local moving = false -- keep track of if ball already moving
 
local xTouch = 0
local yTouch = 0
 
 
-- This function moves the ball each frame
 
function moveHero()
 
	-- Use trig to work out the move
	-- The move variable is the hypotenuse
	-- First work out the angle
 
	local xDiff = xTouch - hero:getX()
	local yDiff = yTouch - hero:getY()
 
	local angle = math.atan2(yDiff,xDiff)
 
	local nextX = hero:getX() + (math.cos(angle) * move)
	local nextY = hero:getY() + (math.sin(angle) * move)
 
	hero:setPosition(nextX,nextY)
 
	-- Reached touch, stop
 
	-- Work out the distance the claw is from hero
 
	local dx = hero:getX() - xTouch;
	local dy = hero:getY() - yTouch;
	local distance = (dx*dx)+(dy*dy)
 
	if(distance <= (5*5)) then
 
		stage:removeEventListener(Event.ENTER_FRAME, moveHero)
		moving = false
 
	end
 
end
 
 
 
 
function touchesEnd(event)
 
	if(moving) then
		stage:removeEventListener(Event.ENTER_FRAME, moveHero)
	end
 
	moving = true
 
	stage:addEventListener(Event.ENTER_FRAME, moveHero) -- add event listener to move ball each frame
	xTouch = event.touch.x
	yTouch = event.touch.y
 
 
end
 
stage:addEventListener(Event.TOUCHES_END, touchesEnd)
+1 -1 (+4 / -0 )Share on Facebook
Sign In or Register to comment.