This page looks best with JavaScript enabled

How to Image Following Mouse in Gideros

 ·  ☕ 2 min read

The idea is quite simple. I subscribe to receive notifications that the mouse has moved and at this point I read the position of the mouse. Then I just have to move my image to near the position where the mouse is.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
-- Below there are 2 auxiliary functions

function Distance(x1,y1, x2,y2)
	return (x2-x1)^2+(y2-y1)^2
end

function Lerp(a, b, t)
	return a + t * (b - a)
end


-- In order to encapsulate the of following the mouse, we are
-- going to create class FollowSprite that is derived from Sprite class.


-- Pay attention to line below. It shows you how to extend a class in Gideros.
FollowSprite = Core.class(Sprite)

-- init() method is the constructor of our class. It will be called when one
-- instantiates FollowSprite (it's done by calling function new()).
--
-- speed parameter adjusts how fast sprite will follow mouse.
-- distance parameter sets how far from mouse sprite will be.
-- texture expects the

function FollowSprite:init(speed, distance, image)
	self.bmp = Bitmap.new(Texture.new(image))
	self.bmp:setAnchorPoint(.5,.5)
	self:addChild(self.bmp)
	self.tx = 0
	self.ty = 0
	self.speed = speed
	self.dist = distance
end

function FollowSprite:follow(x, y)
	self.tx = x
	self.ty = y
end

function FollowSprite:update(dt)
	local x, y = self:getPosition()
	local distSq = Distance(x, y, self.tx, self.ty)

	if (distSq > self.dist^2) then
		local t = 0.1
		x = Lerp(x, self.tx, t)
		y = Lerp(y, self.ty, t)
		self:setPosition(x, y)
	end
end

-- Here we instantiate FollowSprite. Note that it calls init().
local obj = FollowSprite.new(300, 20, 'gideros.png')

stage:addChild(obj)

-- On ENTER_FRAME event we update sprite's position.
stage:addEventListener(Event.ENTER_FRAME, function(e)
	local dt = e.deltaTime
	obj:update(dt)
end)

-- On MOUSE_HOVER event, we update sprite position when mouse moves.
stage:addEventListener(Event.MOUSE_HOVER, function(e)
	obj:follow(e.x, e.y)
end)

In the image below you can see the image by following the mouse.

Image following the mouse in Gideros

The complete project can be downloaded from Plicatibu’s github repository. Read the comments in the main.lua file to see instructions on how to set properties of both project and Gideros player.

Previous post in this series of snippets: How to Move An Image in Gideros

Share on

Márcio Andrey Oliveira
WRITTEN BY
Márcio Andrey Oliveira
Passionate about coding, languages, electronics...