0

I'm currently making a game in Unity where I want the player to have the ability to drag objects troughout the screen based on the touch position. I created a script in order to do this and from what I know it doens't have any mistakes and should allow me to drag the object that the script is attatched to across the screen. However when I try to execute the code nothing happens. when touched the object remains static and doesn't move at all. I even tried to switch it the Input.GetTouch(0).position to Input.mousePosition to see that the problem lied with my phone but this doenst work either. Does anyone know how I might be able to solve this?

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class MoveBall : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public static GameObject WhiteBall;
    Vector3 startPosition;

    #region IBeginDragHandler implementation

    public void OnBeginDrag(PointerEventData eventData)
    {
        WhiteBall = gameObject;
        startPosition = transform.position;
    }

    #endregion

    #region IDragHandler implementation

    public void OnDrag(PointerEventData eventData)
    {
        transform.position = Input.GetTouch(0).position;

    }

    #endregion

    #region IEndDragHandler implementation

    public void OnEndDrag(PointerEventData eventData)
    {
        WhiteBall = null;
        transform.position = startPosition;
    }

    #endregion



}
Maurice Bekambo
  • 325
  • 6
  • 21

1 Answers1

2

Even though you want touch input for your mobile device, you can use the OnMouseDrag function. Just attach a collider to your gameObject and simplify your code to the following:

using UnityEngine;

public class MoveBall : MonoBehaviour
{

    private void OnMouseDrag()
    {
        Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        transform.position = mousePos;
    }
}
Sean Carey
  • 799
  • 5
  • 12
  • Hi thanks for your response. Yes the script is attatched to my game object. I replaced the code with the one you showed and it still doesn't move – Maurice Bekambo Feb 17 '19 at 22:17
  • 1
    @MauriceBekambo I didn't ask if there's a script attached to your game object. I asked if there was a collider attached to your game object. – Sean Carey Feb 17 '19 at 22:18
  • Ah yeah, I just attatched the collider and now it works. Thanks man – Maurice Bekambo Feb 17 '19 at 22:19
  • But just one question when I replace the input.mousePosition with Input.GetTouch(0).position in your code it doesn't work again. You know why this might be? – Maurice Bekambo Feb 17 '19 at 22:25
  • @MauriceBekambo If you _don't_ replace Input.mousePosition with Input.GetTouch, will it work anyways? Try it on your phone. Maybe Unity will swap the methods internally. – Sean Carey Feb 17 '19 at 22:38