How to detect a click on a sprite

From MiniScript Wiki
Revision as of 14:14, 8 March 2020 by JoeStrout (talk | contribs) (Created page with "To detect a mouse click on a sprite, give the sprite a localBounds, and then call .contains on the sprite, passing in mouse. Th...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

To detect a mouse click on a sprite, give the sprite a localBounds, and then call .contains on the sprite, passing in mouse. This returns true when the mouse is over the sprite. You can then use mouse.button to detect when the mouse button is pressed.

Note that you define the localBounds in relation to the sprite's unscaled, non-rotated image. The .contains check uses the sprite's Sprite.worldBounds, so it automatically takes scale, rotation, and position into account for you.

Example

This example creates a rectangular sprite that acts somewhat like a button, highlighting when you mouse over it, and printing a message when clicked.

clear
sp = new Sprite
sp.image = file.loadImage("/sys/pics/Block.png")
sp.x = 600
sp.y = 500
sp.scale = [3,1]
sp.localBounds = new Bounds
sp.localBounds.width = sp.image.width
sp.localBounds.height = sp.image.height
display(4).sprites.push sp
wasDown = false
while true  // press Control-C to exit
	if sp.contains(mouse) then
		sp.tint = "#CCCCFF"
		if mouse.button and not wasDown then
			print "Sprite clicked!"
		end if
	else
		sp.tint = color.white		
	end if
	wasDown = mouse.button
	yield	
end while