Dragging an object with the mouse

BlitzPlus Forums/BlitzPlus Programming/Dragging an object with the mouse

Hello,

I`ve got a small problem with dragging an object, hopefully someone can help tell me why that this is happening.
The problem is that I have an object on the screen and I want to be able to move it by firstly clicking on it
and while the mouse button is still pressed down I want it to follow the mouse and be release in it`s new
location when I release the mouse button. Sounds simple enough.

I have hidden the pointer and loaded an image to replace it so that I can detect a collision between it and
the object.

Here`s the code and the problem.

;-------------------------------
if imagesoverlap(pointer,mousex(),mousey(),object,xpos,ypos) and mousedown(1)
xpos=mousex()
ypos=mousey()
endif

drawimage object,xpos,ypos
drawimage pointer,mousex(),mousey()
;-------------------------------

This works to some extent but the problem is that when I move the mouse to fast the object is droppped when
I really want it to stay with the mouse until I let go of the mouse button.

Any ideas on the cause of this and how I could rectify the problem?

Thanks,
Jason.

Only check for images collide when the mouse is first pressed down, if it is do the drag till the mouse is no longer down.

You will need to use a variable to keep track of if the mouse is 'dragging'

try the following

if imagesoverlap(pointer,mousex(),mouse(),object,xpos,ypos) and mousedown(1) or mousedown(1) and drag = 1 then
xpos=mousex()
ypos=mousey()
drag = 1
else
drag = 0
endif

try this piece of code.the cx and cy stuff are just so when you start dragging the image, it doesn't jump to the mouse's location :)

Graphics 800,600




pointer=CreateImage(2,2)
SetBuffer ImageBuffer(pointer)
Color 140,140,180
Rect 0,0,2,2,1
Color 255,255,255

image=CreateImage(10,10)
SetBuffer ImageBuffer(image)
Rect 0,0,10,10,1
ix=300
iy=300

cx=0;offset for dragging
cy=0;offset for dragging

SetBuffer BackBuffer()

While Not KeyHit(1)
Cls

	If MouseDown(1) Then
		If ImagesOverlap(pointer,MouseX(),MouseY(),image,ix+cx,iy+cy) And drag=0 Then
				drag=1
				cx=ix-MouseX()
				cy=iy-MouseY()
		End If
	Else
		drag=0
		ix=ix+cx
		iy=iy+cy
		cx=0
		cy=0
	End If
	
	
	If drag=1 Then
		ix=MouseX()
		iy=MouseY()
	End If
	
	
	DrawImage image,ix+cx,iy+cy
	DrawImage pointer,MouseX(),MouseY()
	Flip
Wend



Thanks for the help, now it works :)
Jason.