Touch to move

Hi. I’m trying to conduct a little project for android but I’ve reached an issue. I’m trying to have my character move along a terrain so I made it to where if you click somewhere, a marker appears at the location and your character automatically follows it, as this script does:

function Update () {
     for (var i = 0; i < Input.touchCount; i++) {
         if (Input.GetTouch(i).phase == TouchPhase.Moved) {
             var touchPos : Vector3 = Input.GetTouch(i).position;
             touchPos.z = 4.0;
             touchPos.y *= 4.0;
             var createPos = myCam.ScreenToWorldPoint(touchPos);
             projectile.position = createPos;

I also set up 2 cameras; one that follows the player and another that is at a top-down angle facing the terrain and character (which is the one that is referenced to in the script), both of which are orthographic. My problem is that I can’t seem to get the touch marker to move/conform along the terrain, or if there’s a high area the marker would just go through it, as it doesn’t change its Y value if part of the terrain is raised. How would I go about accurately pinpointing the touch location in relation to the 3d environment? I’ve tried placing the marker high up and raycasting downwards but the touch part wouldn’t respond at all, or very poorly.

I’d suggest to use raycast to detect the exact point where the tpuch and the terrain collides.

Something like should work :

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit[] hits = Physics.RaycastAll(ray, 200);

foreach(RaycastHit hit in hits) {
	if(hit.collider.CompareTag("Terrain")) Debug.Log(hit.point);


Instead the mouse position, use your touch position.

Of course you could set the raycast to only detect the layers you want, this will detect the terrain point even if you touch over other object as long as the terrain is in the ray.

Hope this helps

I’ve never used it, but what you want to do is query the terrain height at a particular world position. If you’re using the Unity terrain system, there’s a call for that.

Your touchPos has no height component i.e the Input.GetTouch(i).position provides the ScreenSpace positions which is (pixelWidth,pixelHeight) like a vector2 so when your changing screen to world point that function has no height to it which then sets to zero you can Debug.Log(createPos).

You can use Physics RayCasts for this job. But if you have Unity 5 then you can download there standard assets which already has the kind of controller (like strategy games Civilization, Dota).