Search Unity

How do i stop my player from teleporting with touch controls

Discussion in 'Scripting' started by TolBeardBoi, Oct 7, 2019.

  1. TolBeardBoi

    TolBeardBoi

    Joined:
    Sep 30, 2019
    Posts:
    3
    Im making a 3D avoid the blocks sort of game as im learning and i want my script to make the cube follow my finger when placed on the screen (which works) but since its following where ever i place my finger it will teleport to any new location instead of just smoothly going to where are finger is. It follows my finger but every time i release my finger and put it back down it will teleport to that new position, Which obviously i dont want. I also want to restrict the amount i can move the cube from side to side but dont know how :(

    Code (CSharp):
    1.  void Update()
    2.     {
    3.  
    4.  
    5.         if (Input.GetMouseButton(0) || Input.touchCount > 0)
    6.         {
    7.  
    8.        
    9.             Vector3 screenPos = Input.mousePosition;
    10.          
    11.             screenPos.z = 10.0f;
    12.            
    13.             Vector3 worldPos = Camera.main.ScreenToWorldPoint(screenPos);
    14.  
    15.          
    16.             Vector3 newPos = transform.position;
    17.  
    18.             newPos.x = worldPos.x;
    19.          
    20.             transform.position = newPos;
    21.  
    22.         }
    23.     }
    24.  
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
  3. TolBeardBoi

    TolBeardBoi

    Joined:
    Sep 30, 2019
    Posts:
    3
    Thanks! this worked really well, except im now running into the problem where i can move the block anywhere on the screen instead of just along the x axis, i have both the y and z axis frozen on his rigid body but can still move anywhere.. Also i can just go through the walls and colliders i have set in place?
     
  4. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Well freezing the y and z axis on the rigidbody only does anything when you use the physics system for movement. That would mean adding forces or adjusting the velocity. But physics movement I'm sure is not what you're looking for here.

    Instead I believe you should just be making sure the object's current y and z position and its destination y and z position are the same before doing any movement. Alternatively you could do the movement and then set the y and z values manually to the original y and z values.