Question by
Master_Zen · Dec 11, 2018 at 10:02 AM ·
cameratouchscreentoworldpoint
Is there an easier way to do this?
just as the caption says.
Vector3 worldPointDelta = Camera.main.ScreenToWorldPoint(Input.touches[0].position) -
Camera.main.ScreenToWorldPoint(Input.touches[0].position - Input.touches[0].deltaPosition);
transform.position += worldPointDelta;
this code snippet is supposed to move a player realtive to the first touch on the screen. But the way i do it seems kinda unecessarily complicated. Is there an easier way?
Comment
Answer by Master_Zen · Dec 11, 2018 at 12:58 PM
Okay, i found a better solution myself.
if (Input.touchCount > 0) {
const float MIN_DISTANCE_TO_BORDER = .3f;
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began) {
fingerOffset = Camera.main.ScreenToWorldPoint(Input.touches[0].position) - transform.position;
} else if (touch.phase == TouchPhase.Moved) {
Vector3 newPosition = (Vector2) Camera.main.ScreenToWorldPoint(Input.touches[0].position) - fingerOffset;
transform.position = new Vector3(
Mathf.Clamp(newPosition.x ,-SCREEN_X + MIN_DISTANCE_TO_BORDER, SCREEN_X - MIN_DISTANCE_TO_BORDER),
Mathf.Clamp(newPosition.y, -SCREEN_Y + MIN_DISTANCE_TO_BORDER, SCREEN_Y - MIN_DISTANCE_TO_BORDER),
0f);
fingerOffset = Camera.main.ScreenToWorldPoint(Input.touches[0].position) - transform.position;
}
now the player moves just as the finger stopping at the border and the distance between them updating.