Drag object between two points with mouse

I have a slider where I want to move the handle between two points with the mouse/touch.

The handle is rotated to always face the points so if I could move it in x (localposition) towards the closest point to the mouse and clamp it to not travel outside the two points I would be a happy camper.

Anyone got any ideas how to achieve this, this is what I got so far since I can’t figure out how to move it in a good way.

		Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
		mousePos = new Vector3(mousePos.x,mousePos.y,0f);

		target.rotation = Quaternion.LookRotation(Vector3.forward, sliderLeft.position - sliderRight.position);
		target.Rotate(0f, 0f, -90f);
		target.position = Vector3.MoveTowards(target.position, mousePos, Time.deltaTime * 5f);

1891678--121787--slider.JPG

Exactly like this… I can’t read flash though :smile: Anyone with magic code skills? :wink:
http://wonderfl.net/c/c8Yi

I actually managed to translate the flash script and get it working. So here it is if anyone wants to do something similar sometime.

public transform target; //The draggable buttons transform
public transform sliderLeft; //The sliders left endpoint
public transform sliderRight; //The sliders right endpoint

	public void UpdateSlider() {
		float vX = 0f;
		float vY = 0f;
		float dX = 0f;
		float dY = 0f;
		float iX = 0f;
		float iY = 0f;
		float dotV = 0f;
		float t = 0f;

		Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

		vX = sliderRight.position.x - sliderLeft.position.x;
		vY = sliderRight.position.y - sliderLeft.position.y;

		dX = mousePos.x - sliderLeft.position.x;
		dY = mousePos.y - sliderLeft.position.y;

		dotV = vX * dX + vY * dY;
		t = dotV / (vX * vX + vY * vY);
		t = Mathf.Clamp(t, 0f, 1f);

		iX = sliderLeft.position.x + vX * t;
		iY = sliderLeft.position.y + vY * t;
	
		target.position = Vector3.MoveTowards(target.position, new Vector3(iX, iY, 0f), Time.deltaTime * 5f);
	}
3 Likes

I’ve been looking for this for days and there was not a single person solving this! Thanks a lot!

Please, use the like button to show your appreciation, it’s what it’s for! Nobody needs to see a 8 year old thread necroed like this. It’s also against the forum rules.

Thanks.

1 Like