Restricting movement of a 2d object to backward only in UNITY

Updated on December 2, 2017 in [A] 2D
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
0 on December 2, 2017

I’m making a simple project in Unity where there is a Ball attached to a SpringJoint2d component the ball is on an angled slope,like in the image below:


I simply want the user to be able to drag the ball backward along the edge of the slope only,in other words I don’t want the user to be able to move the ball away from the slope or into it.


I’v been trying several ways I thought could do the job hers the script of the dragging with what I tried:

 public class ball : MonoBehaviour {
public Rigidbody2D rb;
private Vector3 start;
private Vector3 end;
private bool isPressed = false;
private void OnMouseDown() {
start = Camera.main.ScreenToWorldPoint(Input.mousePosition); //start.Normalize();
isPressed = true;
rb.isKinematic = true;
private void OnMouseUp() {
isPressed = false;
rb.isKinematic = false;
IEnumerator release() {
yield return new WaitForSeconds(0.1f);
rb.GetComponent().enabled = false;
// Update is called once per frame
void FixedUpdate()
if (isPressed) {
end = Camera.main.ScreenToWorldPoint(Input.mousePosition);
// end.Normalize();
float dist= Vector3.Distance(start,end);
rb.transform.position += Vector3.forward * Time.deltaTime * dist;

I can’t seem to get this to work , any help is appreciated.

  • Liked by