Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Drag_Drop : MonoBehaviour
- {
- private bool isDragging = false;
- private bool isOverplayerdropZone = false;
- private GameObject playerdropZone;
- private Vector2 startPosition;
- // Update is called once per frame
- void Update()
- {
- if (isDragging)
- {
- transform.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
- }
- }
- private void OnCollisionEnter2D(Collision2D collision)
- {
- playerdropZone = collision.gameObject;
- }
- private void OnCollisionExit2D(Collision2D collision)
- {
- isOverplayerdropZone = false;
- playerdropZone = null;
- }
- public void StartDrag()
- {
- startPosition = transform.position;
- isDragging = true;
- }
- public void EndDrag()
- {
- isDragging = false;
- if (isOverplayerdropZone)
- {
- transform.SetParent(playerdropZone.transform, false);
- }
- else
- {
- transform.position = startPosition;
- }
- }
- }
Advertisement
Comments
-
- using UnityEngine;
- public class Drag_Drop : MonoBehaviour
- {
- public bool isDragging = false;
- public Vector2 offset;
- public Vector2 startPosition;
- public Camera cam;
- public GameObject playerdropZone;
- public bool isOverplayerdropZone = false;
- public bool dropInOther = true;
- private void Start()
- {
- startPosition = transform.position;
- }
- private void OnMouseDown()
- {
- isDragging = true;
- offset = GetMousePos() - (Vector2)transform.position;
- }
- private void OnMouseDrag()
- {
- Vector2 targetPos = GetMousePos() - offset;
- transform.position = targetPos;
- }
- private void OnMouseUp()
- {
- isDragging = false;
- }
- private void OnTriggerEnter2D(Collider2D other)
- {
- playerdropZone = other.gameObject;
- isOverplayerdropZone = true;
- }
- private void OnTriggerExit2D(Collider2D other)
- {
- isOverplayerdropZone = false;
- playerdropZone = null;
- }
- private void Update()
- {
- if (isDragging)
- {
- if (isOverplayerdropZone)
- {
- transform.SetParent(playerdropZone.transform,false);
- transform.localPosition = Vector3.zero;
- }
- }
- else
- {
- if (!dropInOther)
- {
- transform.SetParent(null);
- transform.position = startPosition;
- }
- }
- }
- private Vector2 GetMousePos()
- {
- var flippedCamZ = -cam.transform.position.z;
- return cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, flippedCamZ));
- }
- }
Add Comment
Please, Sign In to add comment
Advertisement