Search Unity

Draging a Cube with UnityEngine.EventSystems

Discussion in 'Editor & General Support' started by ricardHagerman, Feb 3, 2016.

  1. ricardHagerman

    ricardHagerman

    Joined:
    May 26, 2014
    Posts:
    3
    probably ot the best way to do it but this works
    hopefully someone else will be helped by the attached script

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

    /*
    * 3D project
    * Create a cube
    * Create an empty gameobject and attach an eventsystem to the empty object, add Standalone input module
    * Add a Physics Raycaster to the main camera
    * Add this scrip to the cube
    *
    * Now you can drag the cube in the x and y directons.
    *
    * Add touch input to the eventsystem and it works on ios and android.
    *
    * */

    public class Dragg : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler,IPointerClickHandler,IPointerEnterHandler,IPointerExitHandler
    {

    float dx;
    float dy;
    Vector3 newPos;

    MeshRenderer mesh;

    Color col;
    Color startCol;


    void Start ()
    {
    newPos = Vector3.zero;

    mesh = GetComponent<MeshRenderer> ();
    startCol = mesh.material.color;
    col = Color.blue;
    }

    void Update ()
    {

    }

    public void OnPointerEnter (PointerEventData eventData)
    {
    mesh.material.color = col;
    }

    public void OnPointerExit (PointerEventData eventData)
    {
    if (eventData.dragging)
    {
    return;
    }
    mesh.material.color = startCol;
    }

    public void OnBeginDrag (PointerEventData eventData)
    {
    dx = eventData.pointerPressRaycast.worldPosition.x - transform.position.x;
    dy = eventData.pointerPressRaycast.worldPosition.y - transform.position.y;
    }

    public void OnDrag (PointerEventData eventData)
    {
    newPos.x = eventData.pointerCurrentRaycast.worldPosition.x - dx;
    newPos.y = eventData.pointerCurrentRaycast.worldPosition.y - dy;
    if (eventData.pointerCurrentRaycast.worldPosition.x == 0 || eventData.pointerCurrentRaycast.worldPosition.y == 0)
    {
    newPos.x = eventData.delta.x;
    newPos.y = eventData.delta.y;

    transform.Translate (newPos * Time.deltaTime);
    return;
    }
    transform.position = newPos;
    }

    public void OnEndDrag (PointerEventData eventData)
    {
    Debug.Log ("OnEndDrag");
    }

    public void OnPointerClick (PointerEventData eventData)
    {

    Debug.Log ("OnPointerClick");
    }
    }
     

    Attached Files:

    vedram likes this.