- Home /
Duplicate Question
Help With Touch to Drag Script
I currently have a script to move an object by dragging it with the IOS touch input. I want the script to be able to move my object even if your finger is not touching the object. So you can be able to drag the object around even if your finger is below, on top of it... etc.. However, when I use this script and I touch like below or above and try to drag, it transforms the position of the object to my finger. Ill post the script and if someone can help me with it thatd be appreciated. Thanks
#pragma strict
function Start () {
}
function Update () {
for (var touch : Touch in Input.touches){
var ray = Camera.main.ScreenPointToRay(touch.position);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 100)) {
if(touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved) {
var cameraTransform = Camera.main.transform.InverseTransformPoint(0, 0, 0);
transform.position = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, cameraTransform.z - 0.5));
}
}
}
}
Typically in TouchPhase.Began, you calculate an offset from the finger position to the object. As the finger is moved, you position at the finger position plus the offset.
And what's up with line 14? This calculation is just the position of the camera (Camera.main.transform.position).
line 14 is used to make a var which is used in 16 to keep the dot under the camera.
Answer by lblaz · Sep 28, 2013 at 06:24 AM
Solved. Changed the script var object : GameObject;
var speed:float = 0.0001;
function Update () {
if (iPhoneInput.touchCount > 0 && iPhoneInput.GetTouch(0).phase == iPhoneTouchPhase.Moved) {
var touchDeltaPosition:Vector3 = iPhoneInput.GetTouch(0).deltaPosition;
transform.Translate (touchDeltaPosition.x * speed/3, touchDeltaPosition.y * speed/3, 0);
}
}
Solving it this way has two potential problems. First deltaPosition is in screen coordinates, so the amount it will move will vary depending on the platform. And second (related) problem is that since you are no longer using world coordinates, your finger will not stay in the same position relative to the object your are dragging.
@robertbu - Can you please guide on how to fix this. I am having same issue.