Snap object to another object? [SOLVED]

E

Electrino

Guest
Hi,

So basically the player is able to drag objects using the mouse. What I'm trying to achieve is; once the dragged object is close to another object, it snaps on top of it. I have working code for this... but the issue I'm having is when I have more than one of the objects in the same room at the same time.

For example, if I have 2 objects (obj_Drag, obj_snapToMe)... and if I have, say, 3 obj_Drag's and 3 obj_snapToMe 's in a room at the same time (all placed at different positions) the draggable objects (i.e., obj_Drag) always try and snap to the first instance obj_snapToMe. They don't snap to the nearest instance. I've tried messing around with the code but I'm not getting anywhere...

Here are my efforts:
Create:
Code:
 range = 5;
Step:
Code:
if distance_to_object(obj_snap) < range
   {
        x = obj_snap.x;
   }
I was trying something using instance_nearest.... but I was getting similar results... any suggestions as to how I'd fix this?
 

NightFrost

Member
Well, you are checking the distance to to nearest obj_snap there, but then you do x = obj_snap.x which just grabs the first instance of the object it can find, and takes its x value. The problem here is you know the distance to nearest, but you don't know which one is the nearest. You must use instance_nearest to collect the id of the nearest one, then check distance to it using distance_to_object.
Code:
var Nearest = instance_nearest(x, y, obj_snap);
if(distance_to_object(Nearest) < range){
    x = Nearest.x;
}
 
Top