- Home /
Move to touch position
I wrote this script to make the object move to the position, where the player touched. It gets the finger position correctly, but does not change it to world point value. If I were to use the original value, the object would move far away.
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public Vector3 realPos;
public Vector3 tempPos;
// Update is called once per frame
void Update () {
if(transform.position != realPos) {
transform.position = Vector3.Lerp (transform.position, realPos, 0.3f);
}
if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) {
Vector3 fingerPos = Input.GetTouch(0).position;
tempPos = fingerPos;
tempPos.z = 0;
realPos = Camera.main.ScreenToWorldPoint(tempPos);
realPos.z = 0;
Debug.Log (tempPos);
}
}
}
Answer by robertbu · Oct 02, 2014 at 06:05 PM
There is a likely problem here. Your code:
tempPos = fingerPos;
tempPos.z = 0;
realPos = Camera.main.ScreenToWorldPoint(tempPos);
realPos.z = 0;
Debug.Log (tempPos);
...will only work for an Orthographic camera. And if want your object to have a 'z' value of 0.0. For a perspective camera, you need to assign the 'z' of tempPos the distance in front of the camera before you call ScreenToWorldPoint(). So if the camera was at -10 and you wanted to find the position at 'z = 0' (10 units in front of the camera):
tempPos.z = 10.0;
realPos = Camera.main.ScreenToWorldPoint(tempPos);
Note for your movement code, you should be using deltaTime.
transform.position = Vector3.Lerp (transform.position, realPos, Time.deltaTime * 6.0);
I get an error saying that argument #3 cannot convert double to expression to type float. I assume time.deltatime is in double units?
Just add 'f' to value. transform.position = Vector3.Lerp (transform.position, realPos, Time.deltaTime * 6.0f);
Your answer
Follow this Question
Related Questions
Unity Car Accelerometer 0 Answers
How do i lock the position of the camera above the player relative to the origin point? 0 Answers
How can i make my crosshair drag behind the camera? 0 Answers
Control the camera with a half of the touch screen 0 Answers
GearVR rotation stutter InputTracking.GetNodeStates 1 Answer