I’ve got this almost working using ScreenPointToRay with the touch position, then casting a ray to get the position of the hit object. This works, but only if you drag slowly. If the touch gets ahead of the object, the ray cast no longer hits it and the drag stops.
I thought the solution would be to set a flag, and once the drag starts, continue until the touch ends. The problem is that without getting a raycast hit on an object, there’s no way to get the 3D position. I tried ScreenToWorldPoint to translate the touch to a 3D position, but that doesn’t seem to work the same way casting a ray does. It returns numbers way out of range.
Any suggestions or sample code that might show me how to properly drag an object using touch. Something comparable to the non-iPhone DragRigidbody script would be great.
I found this on a thread here in the forums quite a while ago, and I can’t remember where… This works but I find that the object lags behind the finger even tho’ it follows the path described by the finger.
I dragged a cube around and then abandoned it, not discovering why or what to do about the lag, as I had other things to do:
var object : GameObject;
function Update () {
for (var touch : iPhoneTouch in iPhoneInput.touches){
var ray = Camera.main.ScreenPointToRay(touch.position);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 100)) {
if(touch.phase == iPhoneTouchPhase.Began || touch.phase == iPhoneTouchPhase.Moved) {
var cameraTransform = Camera.main.transform.InverseTransformPoint(0, 0, 0);
object.transform.position = Camera.main.ScreenToWorldPoint(new Vector3 (touch.position.x, touch.position.y, cameraTransform.z - 0.5));
}
}
}
}
Thanks. That did the trick. It was that InverseTransformPoint step that I was missing that was causing me to get incorrect values from ScreenToWorldPoint.
I’m using a different touch controller, adapted from one of the iPhone Standard Assets scripts (I believe it was originally called CameraControl). And I don’t have my iPad yet (shipped two days ago), so all I know is what happens in the simulator, which generally tends to be a bit sluggish. I’ll let you know in a few days.
this is working fine , but how to restrict the y movement…i mean if i would like to drag the chair with the finger only in x and z directions then how to do?and the chair shouldn’t go through the walls (wall has box collider).i have changed the statement object.transform.position = camera.main.ScreenToWorldPoint(new vector3(touch.position.x , 0 , cameraTransform.z))…when i did like this , when i touch the object it is going very far and only in the x direction.could u guide me pls how to drag the chair only in x and z directions and it shouldn’t go through the objects which have colliders…