Search Unity

Question How to map touch point to the 3D unity space

Discussion in 'Input System' started by ZaoTX_himself, May 25, 2023.

  1. ZaoTX_himself

    ZaoTX_himself

    Joined:
    May 21, 2019
    Posts:
    3
    Hi all,

    I need to map the touch point to the unity world space to understand the relative position change.
    Here I want to use Camera.ScreenToWorldPoint to map the touch point to world space in Unity.
    The code below is used to simulate the screen touch using mouse position.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class TestScreenPointToRayTest : MonoBehaviour
    6. {
    7.     Camera cam;
    8.     public GameObject cube;
    9.     public Vector2 MousePos = new Vector3(0, 0);
    10.     Vector3 touchWorldPoint;
    11.     // Start is called before the first frame update
    12.     void Start()
    13.     {
    14.         cam = Camera.main;
    15.     }
    16.  
    17.     // Update is called once per frame
    18.     void Update()
    19.     {
    20.         MousePos = Input.mousePosition;
    21.         Ray ray = cam.ScreenPointToRay(MousePos);
    22.         //ray through camera
    23.         Debug.DrawRay(ray.origin,ray.direction * 1000, Color.yellow);
    24.         //camera to cube
    25.         //Debug.DrawRay(cam.gameObject.transform.position,cube.transform.position);
    26.         touchWorldPoint = cam.ScreenToWorldPoint(MousePos);
    27.         //touch world point to cube
    28.         Debug.DrawRay(touchWorldPoint, cube.transform.position);
    29.         if (touchWorldPoint == cam.ScreenToWorldPoint(MousePos + new Vector2(10, 10))) {
    30.             Debug.Log("ScreenToWorldPoint is wrong");
    31.         }
    32.         if (touchWorldPoint == cam.transform.position) {
    33.             Debug.Log("Touch to world point simply returns the camera position");
    34.         }
    35.  
    36.  
    37.  
    38.     }
    39. }
    With the 2 Debug logs I want to test whether the ScreenToWorldPoint actually returns a position based on the touch position. However, the 2 debug log shows all the time. I am kind of confused. Can anyone help me regarding that problem?

    Best
    ZaoTX
     
  2. ZaoTX_himself

    ZaoTX_himself

    Joined:
    May 21, 2019
    Posts:
    3
    I found the problem. It is important to add cam.nearClipPlane to the input of ScreenToWorldPoint