Help to fix my drag code [SOLVED]

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 Test : MonoBehaviour
{
	Plane plane;
	GameObject cube1;
	
	Vector3 mousePos;
	Touch finger;
	
	Ray ray;
	//RaycastHit hit;
	
	private Vector3 offset;
	
	// 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()
		{
			if (Input.GetButton("Fire1"))
			{
				cube1.gameObject.transform.position = toMousePos();
			}
			
			/*if (Input.touches.Length == 1)
			{
				toMousePos();
				
				if (finger.phase == TouchPhase.Moved)
	    		{
					//cube1.gameObject.transform.Translate(Time.deltaTime * 100.0f * new Vector3(finger.deltaPosition.x, 0, finger.deltaPosition.y));
					cube1.gameObject.transform.position = Time.deltaTime * 100.0f * new Vector3(finger.deltaPosition.x, 0, finger.deltaPosition.y);
				}
			}*/
		}
	// Public function
	
	// Private function
	private Vector3 toMousePos()
	{
		mousePos = Input.mousePosition;
		
		/*if (Input.touches.Length == 1)
		{
			finger = Input.touches[0];
		}*/
		
		ray = Camera.main.ScreenPointToRay(mousePos);
		//ray = Camera.main.ScreenPointToRay(finger.position);
		
		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!).

  • Look the comment (i try to use touch). When i test this on my touch, the cube move at plane center and when i re-try to move, return always on plane center (mentions movements).

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

Thanks!!!

1 Answer

1

If you want the object to not jump to the center, then you have to record the “offset” in a vector3 based on where the user clicks. The object should move to a position relative to where you click, not exactly to that point. That’s your trouble, I think. I don’t know nothin’ about touches, and I don’t understand your second question.

Also, clean up your code, please! That’s probably your biggest problem – that your code has all that commented-out code.

Thanks for the reply. I edit my code and i use this for position: Ray ray; Raycast raycastHit; private void toScreenPointToRay() { ray = Camera.main.ScreenPointToRay(Input.mousePosition); Physics.Raycast(ray, out raycastHit); } cube1.transform.position = raycastHit.point; Work very well!! Thanks.

@Ryty please don't post comment as an answer. this is your final warning next time I'll reject your answer.