Advertisement

# How to Detect When an Object Has Been Circled by a Gesture

Read Time:12 minsLanguages:

You're never too old for a game of Spot the Difference—I remember playing it as a kid, and I now find my wife still plays it occasionally! In this tutorial, we'll look at how to detect when a ring has been drawn around an object, with an algorithm that could be used with mouse, stylus, or touchscreen input.

Note: Although the demos and sourcecode of this tutorial use Flash and AS3, you should be able to use the same techniques and concepts in almost any game development environment.

## Final Result Preview

Let's take a look at the final result we will be working towards. The screen is divided into two images, which are almost identical but not quite. Try to spot the six differences, and circle those on the left image. Good luck!

Note: You do not have to draw a perfect circle! You only need to draw a rough ring or loop around each difference.

Don't have Flash? Check out this video demo:

## Step 1: The Circling Motion

We'll be using some vector calculations in the algorithm. As always, it's good to understand the underlying math before applying it, so here's a brief refresher of vector math.

The image above shows the vector A broken down to its horizontal and vertical components (Ax and Ay, respectively).

Now let's look at the dot product operation, illustrated in the image below. First, you will see the dot product operation between vectors A and B.

To find the angle sandwiched between the two vectors, we can make use of this dot product.

|A| and |B| denote the magnitudes of vectors A and B, so given |A| and |B| and A dot B, what's left unknown is theta. With a little algebra (shown in the image), the final equation is produced, which we can use to find theta.

For more information on vector dot product, do refer to the following Wolfram page.

The other useful operation is cross product. Check out the operation below:

This operation is useful to find whether the sandwiched angle is clockwise or counter-clockwise relative to a specific vector.

Let me elaborate further. For the case of the diagram above, rotation from A to B is clockwise, so A cross B is negative. Rotation of B to A is counter-clockwise, so B cross A is positive. Note that this operation is sequence sensitive. A cross B will produce different result from B cross A.

That's not all. It happens that in many game development platforms' coordinate space, the y-axis is inverted (y increases as we move downwards). So our analysis is reversed, and A cross B will be positive while B cross A is negative.

That's enough revision. Let's get to our algorithm.

## Step 2: Circling Interaction

Players will have to circle the correct detail on the image. Now how do we do that? Before answering this question, we should calculate the angle between two vectors. As you'll now remember, we can use the dot product for this, so we shall implement that equation here.

Here's a demo to illustrate what we're doing. Drag either arrow around to see the feedback.

Let's see how this works. In the code below, I've simply initialised the vectors and a timer, and put some interactive arrows on the screen.

Every 50 milliseconds, the function below is run, and used to update the graphical and text feedback:

You will notice that the magnitude for v1 and v2 are both 1 unit in this scenario (check out line 52 and 53 highlighted above), so I skipped the need to calculate the vectors' magnitude for now.

If you want to see the full source code, check out Demo1.as in the source download.

## Step 3: Detect a Full Circle

Ok, now that we have understood the basic idea, we'll now use it to check whether the player successfully circled a point.

I hope the diagram speaks for itself. The start of the interaction is when the mouse button is pressed, and the end of the interaction is when the mouse button is released.

At every interval (of, say, 0.01 seconds) during the interaction, we'll calculate the angle sandwiched between current and previous vectors. These vectors are constructed from the marker location (where the difference is) to the mouse location at that instance. Add up all these angles (t1, t2, t3 in this case) and if the angle made is 360 degrees at the end of interaction, then the player has drawn a circle.

Of course, you may tweak the definition of a full circle to be 300-340 degrees, giving room for player errors when performing mouse gesture.

Here's a demo for this idea. Drag a circular gesture around the red marker in the middle. You can move the red marker's position using W, A, S, D keys.

## Step 4: The Implementation

Let's examine the implementation for the demo. We'll just look at the important calculations here.

Check out the highlighted code below and match it with the mathematical equation in Step 1. You will notice that the value for arccos sometimes produces Not a Number (NaN) if you skip line 92. Also, constants_value sometimes exceeds 1 due to rounding inaccuracies so we need to manually bring it back to a maximum of 1. Any input number for arccos more than 1 will produce a NaN.

The full source for this can be found in Demo2.as

## Step 5: The Flaw

One issue you may see is that as long as I draw a big circle enclosing the canvas, the marker will be considered circled. I don't neccesarily need to know where the marker is.

Well, to counter this problem, we can check the proximity of the circular motion. If the circle is drawn within the confines of a certain range (the value of which is under your control), only then is it considered a success.

Check out the code below. If ever the user exceeds MIN_DIST (with a value of 60 in this case), then it's considered a random guess.

Again, try to circle the marker. If you think the MIN_DIST is a little unforgiving, it can always be adjusted to suit the image.

## Step 6: Different Shapes

What if the "difference" is not an exact circle? Some might be rectangular, or triangular, or any other shape.
In these cases, instead of using just one marker, we can put up a few:

In the diagram above, two mouse cursors are shown at the top. Starting with the right-most cursor, we'll make a circular clockwise motion to the other end on the left. Note that the path encircles all three markers.

I've also drawn the angles elapsed by this path on each of the markers (light dashes to dark dashes). If all three angles are more than 360 degrees (or whichever value you choose), only then do we count it as a circle.

But that's not enough. Remember the flaw in Step 4? Well, the same goes here: we'll need to check for proximity. Instead of requiring the gesture to not exceed a certain radius of a specific marker, we'll just check whether the mouse cursor came close to all the markers for at least a short instance. I'll use pseudo-code to explain this idea:

## Step 7: Demo for the Idea

Here, we're using three dots to represent a triangle.

Try to circle around:

• one dot
• two dots
• three dots

...in the image below. Take note that the gesture only succeeds if it contains all three dots.

Let's check out the code for this demo. I've highlighted the key lines for the idea below; the full script is in Demo4.as.

## Step 8: Drawing the Circles

The best method for actually drawing the line that you trace will depend on your development platform, so I'll just outline the method we would use in Flash here.

There are two ways to draw lines in AS3, as indicated by the image above.

The first approach is rather simple: use moveTo() to move the drawing position to coordinate (10, 20). Then draw a line to connect (10, 20) to (80, 70) using lineTo().

The second approach is to store all details in two arrays, commands[] and coords[] (with coordinates stored in (x, y) pairs within coords[]) and later draw all graphical details onto canvas using drawPath() in one single shot. I've opted for the second approach in my demo.

Check it out: try to click and drag the mouse on canvas to draw line.

And here's the AS3 code for this demo. Check out the full source in Drawing1.as.

In Flash, using the graphics object for drawing like this uses retained mode rendering, meaning that the properties of the individual lines are stored separately - as opposed to immediate mode rendering, where only the final image is stored. (The same concepts exist in other development platforms; for instance, in HTML5, drawing to SVG uses retained mode, while drawing to canvas uses immediate mode.)

If there are many lines on screen, then storing and re-rendering them all separately may make your game slow and laggy. The solution to this will depend on your platform - in Flash, you can use BitmapData.draw() to store each line in a single bitmap after it has been drawn.

## Step 9: Sample Level

Here I have created a demo for the sample level of a Spot the Difference game. Check it out! The full source is in Sample2.as of the source download.

## Conclusion

Thanks for reading this article; I hope it gave you an idea for building your own game. Do leave some comments if there's any issue with the code and I'll get back to you as soon as possible.

Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.