Difference between revisions of "How to detect a click on a sprite"

From MiniScript Wiki
Jump to navigation Jump to search
Line 2: Line 2:
  
 
Note that you define the [[Sprite.localBounds|localBounds]] in relation to the sprite's unscaled, non-rotated image.  The [[Sprite.contains|.contains]] check uses the sprite's [[Sprite.worldBounds]], so it automatically takes scale, rotation, and position into account for you.
 
Note that you define the [[Sprite.localBounds|localBounds]] in relation to the sprite's unscaled, non-rotated image.  The [[Sprite.contains|.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 [[SpriteDisplay.scrollX|scrollX]] and [[SpriteDisplay.scrollY|scrollY]] values to the mouse position in your [[Sprite.contains|.contains]] test.  So in the example below, <msinline>sp.contains(mouse)</msinline> would change to <msinline>sp.contains(mouse.x + display(4).scrollX, mouse.y + display(4).scrollY)</msinline>.
  
 
== Example ==
 
== Example ==

Revision as of 16:53, 8 March 2020

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
	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

SpriteClickDemo.png