# Snap-Points for dragging to

**URL:** <https://forum.kirupa.com/t/snap-points-for-dragging-to/167664>\
**Category:** open source\
**Created:** [October 30, 2005, 8:46pm UTC](https://forum.kirupa.com/t/snap-points-for-dragging-to/167664 "2005-10-30T20:46:18Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![icio](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/icio/32/484_2.png) [@icio](https://forum.kirupa.com/u/icio)\
**Post date:** [October 30, 2005, 8:46pm UTC](https://forum.kirupa.com/t/snap-points-for-dragging-to/167664/1 "2005-10-30T20:46:18Z")

</div>

I’ve seen a couple of people asking for a method of creating points that objects they are dragging snap to so I whipped something up.

.fla and .swf are attached, but here’s the source for anybody not with Flash 8.

```auto
var snapPoints:Array = []; // Set up our variables
var drag:MovieClip; // `drag` is a movieclip on the Stage.
for (i=0; i<10; i++) {
	snapPoints.push(obj=_root.attachMovie("snapPoint", "point_"+i, _root.getNextHighestDepth())); // Quite a complex line of code, basically it does three things: Creates a MovieClip on the stage from a library instance with linkage "snapPoint", sets `obj` as the MovieClip we've just created and then put that MovieClip into an array
	obj._x = Math.random()*550; // Position the MovieClip randomly around the stage
	obj._y = Math.random()*400;
}
drag.swapDepths(_root.getNextHighestDepth());
_root.onEnterFrame = function() {
	drag._x = _xmouse; //Move the `drag` MovieClip to the cursor.
	drag._y = _ymouse;
	var currDist:Number; // The shortest distance between `drag` and a snapPoint
	for (i in snapPoints) { // Cycle through the snapPoints
		obj = snapPoints*;
		d = Math.sqrt(Math.pow(obj._x-drag._x, 2)+Math.pow(obj._y-drag._y, 2)); // Calculate the distance between the current snapPoint and `drag`
		if (!currDist || d<currDist) { // If `currDist` has not been set yet, or the current distance is shorter than the previously calculated distance, then:
			currDist = d; // Set `currDist` as the current distance - the shortest.
			targ = obj; // Set `targ` as a reference to the 
		}
	}
	if (targ && currDist<10) { // if `targ` has been set and the shortest distance is less than 10, then:
		drag._x = targ._x; // Reposition `drag` to the snapPoint
		drag._y = targ._y;
	}
};

```

Enjoy :thumb:  
Hope it helps somebody.
