- "Touching" redirects here. For the block that senses if a sprite is touching a color, see Touching Color ()? (block).
The Touching ()? block is a sensing block and a Boolean block. The block checks if its sprite is touching the mouse-pointer, edge, or another sprite (a reporter block which returns the sprite's name, usually a variable can be used). If the sprite is touching the selected object, the block returns true; if it is not, it returns false.
This block behaves differently when the sprite is hidden. Every check for collisions with other sprites return false, however, it still senses the mouse and the edges.
As the block checks, if its sprite is touching an object, it is widely used in detecting collisions.
Some common uses for the Touching ()? block:
- Moving a sprite until it touches the edge of the screen
repeat until <touching [edge v]?> move (3) steps end
- Having a sprite chase another sprite until the chaser touches the other sprite
repeat until <touching [Sprite2 v]?> point towards [Sprite2 v] move (3) steps end say [I got you!] for (2) secs
- Stopping bullets when they hit walls
In this example, the wall is moving, and the bullet remains fixed.
forever if <touching [wall v]?> then hide
- In a maze, sensing if a sprite has hit a dead-end
forever if <touching [maze walls v]?> then say [Dead end!] for (1) secs
- Checking if a sprite is touching the mouse pointer
when flag clicked forever if <touching [mouse-pointer v]?> then switch costume to [highlighted v] else switch costume to [normal v] end
- Checking if the player has touched an enemy in a game
forever if <touching [Enemy v]?> then say [Game over!] stop [all v] end
Clones Touching Clones
Normally, most blocks targeting other sprites will not act on one of the sprite’s clones, but for the parent sprite. However, with this block, if
<touching [sprite2 v]?> is used in a clone of sprite1, not only will it report true when touching the parent sprite, but also when touching any clone.
Some Scratchers want a block that detects if two different sprites are touching. The advantage of such a block is that it grants a 3rd sprite the ability to sense if another two are touching. Such a block would look similar to this:
<[sprite1 v] is touching [sprite2 v]? ::sensing>
This can be replicated with a global variable, with one of the touching sprites checking, and setting the value, like so:
// In Sprite1 when I receive [Check for Touching v] if <touching [Sprite2 v]?> then set [Sprite1 Touching Sprite2? v] to [yes] else set [Sprite1 Touching Sprite2? v] to [no] end // Place this anywhere to check for the touching broadcast [Check for Touching v] and wait if <(Sprite1 Touching Sprite2?) = [yes]> then // put the desired output if touching here else // put what you want if they aren't here end
- Ask_Pinkamena. (19/7/2015). “Sprite touching anything.[title]” https://scratch.mit.edu/discuss/topic/135012/