Help to fix my drag code

Hello all, i’m new to unity3d (fantastic engine and tools!!). I write this code for drag cube in a scene:

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {
	
	Plane plane;
	GameObject cube1;
	
	Vector3 mousePos;
	
	Ray ray;
	RaycastHit raycastHit;
	
	// Public function

       // Use this for initialization

       void Start()

        {

         plane = new Plane(Vector3.up, Vector3.zero);

         cube1 = GameObject.Find("Cube1");

       }

 

       // Update is called once per frame

       void Update()

       {
		Vector3 temp = toScreenPosInWorldPos();

         if (Input.GetButton("Fire1"))

         {

          //cube1.transform.position = toScreenPosInWorldPos();
			
			cube1.transform.position = new Vector3 (temp.x, temp.y + cube1.transform.position.y, temp.z); 

         }
		
		if (Input.touches.Length == 1)
		{
    		Touch finger = Input.touches[0];
			
			if (finger.phase == TouchPhase.Moved)
       		{
				cube1.transform.position = new Vector3 (temp.x, temp.y + cube1.transform.position.y, temp.z); 
       		}
    	}

       }

    // Public function

 

    // Private function

    private Vector3 toScreenPosInWorldPos()

    {

       mousePos = Input.mousePosition;

 

       ray = Camera.main.ScreenPointToRay(mousePos);

 

       float distance;

 

       if (plane.Raycast(ray, out distance))

       {

         Debug.Log(distance);

 

         return ray.GetPoint(distance);

       }

 

       return Vector3.zero;

    }

    // Private function
}
  • It works well, but has problem with the object “y”, when i press a mouse button the drag start at object center and not bottom… How to fix this? (The value of y should not change!).

And… my code is right in this way (i’m on the right road) or exist “professional alternative” for drag?.

Thanks!!!

Anyone? I would move my cube in x z axis in same mouse position…help please

transform.position is the center of the gameObject.

Offset your position to account for that:

Vector3 temp = toMousePos();
transform.position = new Vector3 (temp.x, temp.y + 1, temp.z);

Thanks i edit my code in first post for all people…function very well thanks! =)