SNoV
SNoV

Reputation: 97

How to drag unity object just up-down and left-right .?

I have a graph in unity, I want to drag it just up-down and left-right to see upcoming coordinates.

I wrote this code to drag the graph object but it drags it all around without a limit. I just want it to go just up-down and left-right.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DragGraph : MonoBehaviour {

    float OffsetX;
    float OffsetY;

    public void BeginDrag(){
        OffsetX = transform.position.x - Input.mousePosition.x;
        OffsetY = transform.position.y - Input.mousePosition.y;
    }

    public void OnDrag(){

        transform.position = new Vector3 (OffsetX + Input.mousePosition.x, OffsetY + Input.mousePosition.y);

    }

}

Upvotes: 1

Views: 1556

Answers (2)

joel64
joel64

Reputation: 387

If you want it to go up and down then why are you using the x value? You could just leave it 0 it and only the y value will change and make it go up and down.

Edit Not sure if this is ideal but its similar to a swipe up, down, left and right.I tried it and it goes in one direction at a time.

 Vector2 offset;
Vector2 startPos = Vector2.zero;

public void OnBeginDrag(PointerEventData eventData)
{
    startPos = eventData.position;
    offset.x = transform.position.x - Input.mousePosition.x;
    offset.y = transform.position.y - Input.mousePosition.y;
}

public void OnDrag(PointerEventData eventData)
{
    Vector2 direction = eventData.position - startPos;
    direction.Normalize();

    if ((direction.x>0 || direction.x<0) && direction.y>-0.5f && direction.y < 0.5f)
    {
        transform.position = new Vector3(offset.x+ Input.mousePosition.x, transform.position.y);
    }
    if ((direction.y > 0 || direction.y<0) && direction.x > -0.5f && direction.x < 0.5f)
    {
        transform.position = new Vector3( transform.position.x, offset.y + Input.mousePosition.y);
    }
}

Upvotes: 0

if OffsetX > OffsetY, don't use Input.mousePosition.y

And vice versa.

Figuring out what to do when OffsetX == OffsetY is left as an exercise to the reader.

Upvotes: 1

Related Questions