Drag sprite only diagonally only.

any idea how to do this? All i know is i need to change some code on onmousedrag but i do not know how.

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

public class FirstPart : MonoBehaviour
{
    [SerializeField]
    private Transform redPlace;

    private Vector2 initialPosition;

    private Vector2 mousePosition;

    private float deltaX, deltaY;

    public static bool locked;

   

    void Start()
    {
        initialPosition = transform.position;
    }

    private void OnMouseDown()
    {
        if (!locked)
        {
            deltaX = Camera.main.ScreenToWorldPoint(Input.mousePosition).x - transform.position.x;
            deltaY = Camera.main.ScreenToWorldPoint(Input.mousePosition).y - transform.position.y;
        }
    }

    private void OnMouseDrag()
    {
       
        if (!locked)
        {
            mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
             transform.position = new Vector2(mousePosition.x - deltaX, mousePosition.y - deltaY);
   
        }

    }

    private void OnMouseUp()
    {
        if (Mathf.Abs(transform.position.x - redPlace.position.x) <= 0.5f &&
                   Mathf.Abs(transform.position.y - redPlace.position.y) <= 0.5f)
        {
            transform.position = new Vector2(redPlace.position.x, redPlace.position.y);
            locked = true;
        }
        else
        {
            transform.position = new Vector2(initialPosition.x, initialPosition.y);
        }
    }

First, I would not write code like this… it’s a bit on the hairy side.

How to break down hairy lines of code:

http://plbm.com/?p=248

Break it up, practice social distancing in your code, one thing per line please.

In this case, break out the intended motion into a single Vector3 variable, let’s call it motion.

Then move the thing by that motion vector.

Once you have that nicely cleaned up and fully proven to work again, it becomes trivial to do something like this:

// find largest magnitude motion
var largest = Mathf.Max( Mathf.Abs( motion.x), Mathf.Abs( motion.y));

// recreate a diagonal with that scale of motion while preserving sign
motion.x = MySign( motion.x) * largest;
motion.y = MySign( motion.y) * largest;

Now usemotion to do the movement.

EDIT:

Also need a modified Sign() that never returns zero: add this method:

static float MySign( float x)
{
 if (x < 0) return -1;
 return 1;
}
1 Like