- Home /
Question by
jy_erwewrwrew · Oct 14, 2021 at 01:58 PM ·
spriteunity 2dmousepositionmouse-drag
How to I mouse Drag sprite diagonally only?
Been trying the whole day today, but i still couldnt figure out. i think i only need to change the code 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);
}
}
}
Comment
Your answer
Follow this Question
Related Questions
How do I get the Vector2 from an input action in code? (New Input System) 1 Answer
Unity2D resize the sprite 0 Answers
How can I instantiate a different sprite depending on where Raycasting goes? 0 Answers
Moving Rigidbody2D relative to the mouse. 1 Answer
Setting a sprite's size with pixels 2 Answers