How to detect a click on a sprite

From MiniScript Wiki
Revision as of 15:06, 5 November 2021 by JoeStrout (talk | contribs) (fixed example to be more reliable)
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.

Dealing with a scrolled display

If your SpriteDisplay is scrolled, then you would need to add its scrollX and scrollY values to the mouse position in your .contains test. So in the example below, sp.contains(mouse) would change to sp.contains(mouse.x + display(4).scrollX, mouse.y + display(4).scrollY).

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
	isDown = mouse.button
	if sp.contains(mouse) then
		sp.tint = "#CCCCFF"
		if isDown and not wasDown then
			print "Sprite clicked!"
		end if
	else
		sp.tint = color.white		
	end if
	wasDown = isDown
	yield	
end while

SpriteClickDemo.png