How to make SWIPE DETECTION in Scratch!

Share

Summary

This tutorial teaches how to implement swipe detection in Scratch using a custom block, variables, and sprite manipulation. It covers creating a draggable rectangle, calculating swipe distance and direction, and using this information to trigger actions.

Highlights

Setting up the Project and Initial Sprite
00:00:06

Start by creating a new Scratch project. Draw a rectangle sprite, ensuring its origin (X:0, Y:0) is at the center. Make the sprite draggable and place it at X:0, Y:0 initially. Duplicate this sprite twice to create three identical rectangles.

Introducing Custom Block and Variables
00:00:41

Create a custom block named 'Swipe Detection' with two string inputs, 'Threshold' and 'Speed'. This block will handle the core logic. Initialize three variables: 'Start X', 'Start Y', and 'Swipe X'. 'Swipe X' will be used to determine the swipe direction and distance.

Handling Sprite Layering and Position Lock
00:01:38

Add 'go to front layer' and 'set x to 0' blocks directly under the 'when green flag clicked' event for the main sprite. Unlock all sprites except for the main one, which should be locked at X:0, Y:0. This ensures only the main sprite is draggable and its movement is controlled.

Calculating Swipe Distance and Setting a Threshold
00:02:16

When the sprite is clicked, set 'Start X' to the current mouse X position. When the sprite is released, calculate 'Swipe X' by subtracting 'Start X' from the current mouse X position. This 'Swipe X' value represents the horizontal swipe distance. Divide 'Swipe X' by 24 for a practical movement value. The swipe threshold is 77, meaning a swipe needs to move at least 77 units horizontally to be registered.

Implementing Swipe Movement
00:03:00

To move the duplicated sprites, set 'x' for those sprites to 'x position' of the main sprite plus 480 or minus 480, depending on whether they are to the left or right. Use a 'repeat until' loop to animate the swipe, moving the sprites by 'Swipe X' slowly until they reach their target positions. For a smooth animation, multiply 'Swipe X' by 0.1 and use the operator 'round' to ensure gradual movement.

Considering Edge Cases and Final Touches
00:04:15

After a swipe, unlock all sprites. Before a new swipe, relock the two duplicate sprites by sending them behind the main sprite, effectively hiding them. This prevents unintended interactions. Also, when a sprite reaches an edge (-900 or 900), ensure it correctly repositions to the other side (e.g., -480 or 480) to create an infinite swipe effect. Use 'if-else' blocks to handle swipe left and swipe right conditions.

Recently Summarized Articles

Loading...