Game Object does not retain its original position when left in space on drag n drop in unity - c#

There is a game Object "Heat" in Unity 2D. I am trying to drag and drop game object on another game object Sun using UI(works for unity version greater than 4.6). Drag works right but when I drop the object in space other than Sun, heat object does not retain its original position. I tried to make it work using colliders and raycasting but it does not seem to work. Here is the code:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class Drag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {
public static GameObject itemBeingDragged;
public static Vector2 startPos;
void Start () {
}
#region IBeginDragHandler implementation
public void OnBeginDrag (PointerEventData eventData)
{
itemBeingDragged = gameObject;
startPos = transform.position;
}
#endregion
#region IDragHandler implementation
public void OnDrag (PointerEventData eventData)
{
transform.position = eventData.position;
}
#endregion
#region IEndDragHandler implementation
public void OnEndDrag (PointerEventData eventData)
{
//if itemBeingDragged is in Space then move it to its original position and then assign null
//itemBeingDragged = null;
RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint (Input.mousePosition), Vector2.zero);
if (hit.collider != null)
{
print ("Inside hit.collider" + hit.collider.name);
//Itembeing Dragged ... set it to startPos if released in space
if (hit.collider.gameObject.name == "Heat")
{
LeanTween.move (hit.collider.gameObject,PublicVariables.startPosHeat, 1.5f);
}
}
}
#endregion
}
Any help is much appreciated. Thanks.

Related

ScreenToWorld point on 2d scale without affecting the Z position

I'm creating a draggable item but whenever I drag it's z position would become 47 and I wanted it to retain to 0.
using UnityEngine;
using UnityEngine.EventSystems;
public class draggableItem : MonoBehaviour, IBeginDragHandler, IDragHandler , IEndDragHandler
{
Transform setParentAferDrag;
public void OnBeginDrag(PointerEventData eventData)
{
setParentAferDrag = transform.parent;
transform.SetParent(transform.root);
transform.SetAsLastSibling();
}
public void OnDrag(PointerEventData eventData)
{
var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = mousePos;
}
public void OnEndDrag(PointerEventData eventData)
{
transform.SetParent(setParentAferDrag);
}
}

Unity C# Dragged item positions itself a few centimeters above mouse mosition

So I have a script (For drag and drop inventory system) that was working fine yesterday, but this morning the Items being dragged no longer followed the mouse pointer at the crusors position but instead followed it with a at a distance. So upon clicking the item, nothing happened, once i start dragging the item x,y values just changed and placed itself a few centimeters above the crusor whilst still following the crusor.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class DragHandler : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public static GameObject itemBeingDragged;
Vector2 startPosition;
Transform startParent;
public void OnBeginDrag ( PointerEventData eventData)
{
itemBeingDragged = gameObject;
startPosition = transform.position;
startParent = transform.parent;
GetComponent<CanvasGroup>().blocksRaycasts = false;
}
public void OnDrag (PointerEventData eventData)
{
transform.position = Input.mousePosition;
}
public void OnEndDrag (PointerEventData eventData)
{
itemBeingDragged = null;
GetComponent<CanvasGroup>().blocksRaycasts = true;
if (transform.parent == startParent)
{
transform.position = startPosition;
}
}
}
ยดยดยด
When you drag an item, the mouse can be anywhere inside the item. You should therefore calculate the delta between the mouse position and the position of the dragged item. You can then add this delta in the OnDrag() functions when setting a new position.
Vector3 delta;
public void OnBeginDrag(PointerEventData eventData)
{
itemBeingDragged = gameObject;
delta = itemBeingDragged.transform.position -
new Vector3(eventData.pressPosition.x, eventData.pressPosition.y, 0);
// ....
}
...
public void OnDrag(PointerEventData eventData)
{
transform.position = Input.mousePosition + delta;
}
Note that we should not use the Input.mousePosition in the OnBeginDrag() since the drag operation starts first after the mouse has moved a bit. We could of course calculate the delta as soon as the mouse button was pressed, and then we can use the Input.mousePosition. But, since you use the OnBeginDrag() we use the event's pressPosition which is the mousePosition when pressed.

I want to move 2d object only horizontally by touch in Unity

I implemented a touch drag.
But I can not move only horizontally.
I would expect to limit it to if, but I do not know what to do after that.
Here is my code.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.EventSystems;
public class Draggable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public void OnBeginDrag (PointerEventData eventData)
{
Debug.Log ("OnBeginDrag");
}
public void OnDrag (PointerEventData eventData)
{
Debug.Log ("OnBeginDrag");
//this.transform.position = eventData.position;
GetComponent<Transform> ().position = eventData.position;
}
public void OnEndDrag (PointerEventData evnetData)
{
Debug.Log ("OnEndDrag");
}
}
You don't need to call GetComponent for transform.
If the code you were using works and you just want horizontal drag, something like this should work.
var currentPos = transform.position;
transform.position = new Vector3(eventData.position.x, currentPos.y, currentPos.z);

How to compare name of a GameObject in Unity

So I'm making simple game to put the right answer in the right slot. which is when you put the right sticker on the slot you got score.
for the example if you put the sticker "a" to the slot "b" then you got point. and then the sticker "a", the sticker become child of slot "b".
the problem is when i uses the name of the gameobject it doesnt work, i tried using debug.log to show the score but it doesnt work. this script is component of the slot. the draghandler is from another script the script is component of the sticker.
Here is the code
public void OnDrop (PointerEventData eventData)
{
if (!item) {
DragHandler.itemBeingDragged.transform.SetParent (transform);
if (DragHandler.itemBeingDragged.gameObject.name == "b" && DragHandler.itemBeingDragged.transform.parent.name == "slot2") {
score = score + 25;
nilai = score.ToString();
Debug.Log ("score: "+nilai);
}}}
but when i used this code to show the name of slot and the sticker it's work
public void OnDrop (PointerEventData eventData)
{
if (!item) {
DragHandler.itemBeingDragged.transform.SetParent (transform);
Debug.Log ("slot: "+DragHandler.itemBeingDragged.transform.parent.name + "item : "+DragHandler.itemBeingDragged.gameObject.name);
}
}
this is the code for draghandler
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class DragHandler : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler {
public static GameObject itemBeingDragged;
Vector3 startPosition;
Transform startParent;
#region IBeginDragHandler implementation
public void OnBeginDrag (PointerEventData eventData)
{
itemBeingDragged = gameObject;
startPosition = transform.position;
startParent = transform.parent;
GetComponent<CanvasGroup> ().blocksRaycasts = false;
}
#endregion
#region IDragHandler implementation
public void OnDrag (PointerEventData eventData)
{
startPosition = Input.mousePosition;
//Debug.Log ("namanya : " + itemBeingDragged.name);
}
#endregion
#region IEndDragHandler implementation
public void OnEndDrag (PointerEventData eventData)
{
itemBeingDragged = null;
GetComponent<CanvasGroup> ().blocksRaycasts = true;
if (transform.parent == startParent) {
transform.position = startPosition;
}
}
#endregion
}
If there's something missing with my explanation let me know.
Thank you.
I can't see the code for the drag handler but does it drop the item after you release it? If so it may not have the item that WAS being dragged. So maybe when you check the DragHandler.itemBeingDragged it may return null.

Prevent object from jumping to center point when dragging starts

I have a script for dragging GameObjects around, but at the moment, whenever I start to drag on the object it jumps to the center itself onto the pointer. What I'd like to achieve is regardless of where I start to drag on the object it initiates drag at that point instead of jumping to the object center first. What do I need to modify in my OnDrag or OnBeginDrag method to achieve this?
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.EventSystems;
using System.Collections.Generic;
public class DragHandling : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IPointerClickHandler
{
public float partScale;
[HideInInspector] public Transform placeholderParent = null;
[HideInInspector] public Transform parentToReturnTo = null;
[HideInInspector] public GameObject trashCan;
[HideInInspector] public GameObject partsPanel;
[HideInInspector] public GameObject partsWindow;
[HideInInspector] public GameObject buildBoard;
GameObject placeholder = null;
GameObject dragLayer;
Vector3 buildPanelScale;
Vector3 partsPanelScale = new Vector3(1.0f, 1.0f, 1.0f);
Vector3 startPosition;
// PolygonCollider2D collider;
void Start ()
{
dragLayer = GameObject.FindGameObjectWithTag("DragLayer");
buildBoard = GameObject.FindGameObjectWithTag("Board");
partsPanel = GameObject.FindGameObjectWithTag("Parts");
partsWindow = GameObject.FindGameObjectWithTag("PartsWindow");
trashCan = GameObject.FindGameObjectWithTag("Trash");
// collider = transform.GetComponent<PolygonCollider2D>();
}
#region IPointerClickHandler implementation
public void OnPointerClick (PointerEventData eventData)
{
if(transform.parent.gameObject == buildBoard)
transform.SetAsLastSibling();
}
#endregion
#region IBeginDragHandler implementation
public void OnBeginDrag (PointerEventData eventData)
{
// create placeholder gap and hold correct position in layout
placeholder = new GameObject();
placeholder.transform.SetParent(transform.parent);
placeholder.transform.SetSiblingIndex(transform.GetSiblingIndex());
parentToReturnTo = transform.parent; // store original parent location
placeholderParent = parentToReturnTo; // set placeholder gameobject transform
startPosition = transform.position;
GetComponent<CanvasGroup>().blocksRaycasts = false; // turn off image raycasting when dragging image in order to see what's behind the image
}
#endregion
#region IDragHandler implementation
public void OnDrag (PointerEventData eventData)
{
Vector3 mousePosition = new Vector3(eventData.position.x, eventData.position.y, 0);
transform.position = Input.mousePosition; // set object coordinates to mouse coordinates
if(transform.parent.gameObject == partsPanel)
transform.SetParent(dragLayer.transform); // pop object to draglayer to move object out of parts Panel
if(transform.parent.gameObject == buildBoard)
transform.SetParent(dragLayer.transform);
}
#endregion
#region IEndDragHandler implementation
public void OnEndDrag (PointerEventData eventData)
{
transform.SetParent(parentToReturnTo); // Snaps object back to orginal parent if dropped outside of a dropzone
transform.SetSiblingIndex(placeholder.transform.GetSiblingIndex()); // Returns card back to placeholder location
GetComponent<CanvasGroup>().blocksRaycasts = true; // turn Raycast back on
Destroy(placeholder); // kill the placeholder if object hits a drop zone or returns to parts panel
if(transform.parent.gameObject == buildBoard)
{
buildPanelScale = new Vector3(partScale, partScale, partScale);
transform.localScale = buildPanelScale;
transform.SetAsLastSibling(); // always place last piece on top
}
if(transform.parent.gameObject == partsPanel)
transform.localScale = partsPanelScale;
}
#endregion
}
I have never used any interface to implement this, But the solution should be the same as using with OnMouseDown, OnMouseUp and OnMouseDrag with the sprites. Try this with your current implementation
using UnityEngine;
using System.Collections;
public class Drag : MonoBehaviour {
private Vector3 offset = Vector3.zero;
void OnMouseDown () {
Vector3 worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
worldPos.z = transform.position.z;
offset = worldPos - transform.position;
}
void OnMouseDrag () {
Vector3 worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
worldPos.z = transform.position.z;
worldPos = worldPos - offset;
transform.position = worldPos;
}
void OnMouseUp () {
offset = Vector3.zero;
}
}
I have used this with an orthographic camera on Sprites. Hope this helps.
EDIT
Tried implementing the interfaces as in your code with UI elements. It is working as expected. Only thing is to set the canvas to ScreenSpace-Camera implement the code in the respective interfaces
your question is a bit confusing and if im correct you are saying that the object you start to drag keeps moving to the middle of screen , if you dont want that just update the dragged objects transform in OnEndDrag.

Categories