Hey. I am trying to make a script that allows me to drag a object on x axis (which works)but for some reason it transforms on y axis… how to make that y axis would be locked i tried adding a rigidbody but the constrains are not working…
THIS IS MY SCRIPT FOR MOVING IT:
using UnityEngine;
using System.Collections;
public class TouchControl : MonoBehaviour {
float distance = 10;
void OnMouseDrag()
{
Vector3 mousePosition = new Vector3 (Input.mousePosition.x, 250, distance);
Vector3 objPosition = Camera.main.ScreenToWorldPoint (mousePosition);
transform.position = objPosition;
}
}
you should be passing the Input.MousePosition DIrectly in the ScreenToWorldPoint method, than when you apply that position to the object just ignore the z and y axis.
using UnityEngine;
public class TouchControl : MonoBehaviour {
private void OnMouseDrag() {
Vector3 objPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = new Vector3(objPosition.x, transform.position.y, transform.position.z);
}
}
also is a little more future proof but and requires more work, but the more optimial way would to to use the IDragHandler
using UnityEngine;
using UnityEngine.EventSystems;
public class TouchControl : MonoBehaviour, IDragHandler {
public void OnDrag(PointerEventData eventData) {
Vector3 objPosition = Camera.main.ScreenToWorldPoint(eventData.position);
transform.position = new Vector3(objPosition.x, transform.position.y, transform.position.z);
}
}
but doing so also requires you to have a event system in your scene, and a physics raycaster on your camera to work.
Yeah i just ran in to another problem the object i am trying to move when i click on it is transforming on x not to much just a bit(I can move it on x)… and its kinda annoying…