Search Unity

Make world direction represent touch swipe direction

Discussion in 'Scripting' started by Silasi, Dec 31, 2019.

  1. Silasi

    Silasi

    Joined:
    Jul 25, 2016
    Posts:
    48
    Hello there and happy holidays :D

    I have made a script to move the red object to the right by swiping the screen to the right.
    Untitled.png

    But the camera will orbit the object. So if the camera is on the other side, I'll have to move the object to the LEFT by still swiping to the RIGHT, because the swipe direction remains the same.
    Untitled2.png

    How can I make it move to where the pink arrow points so the direction of the arrow and the direction of the swipe remains the same while the camera orbits around 360 degrees?

    This is what I am using:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Move : MonoBehaviour
    6. {
    7.     public LayerMask mask;
    8.     public float sensitivity;
    9.     GameObject selected;
    10.  
    11.     // Update is called once per frame
    12.     void Update()
    13.     {
    14.         OneTouch();
    15.     }
    16.  
    17.     void OneTouch(){
    18.         if(Input.touchCount == 1){
    19.             Touch touch = Input.GetTouch(0);
    20.  
    21.             //ONLY HIT THE RED OBJECT
    22.             Ray ray = Camera.main.ScreenPointToRay(touch.position);
    23.             RaycastHit hit;
    24.             if(Physics.Raycast(ray, out hit, 50f, mask)){
    25.                 selected = hit.transform.gameObject;
    26.             }
    27.              
    28.             //MOVE THE X TO -1.5
    29.             if(touch.phase == TouchPhase.Moved){
    30.                 Vector3 direction = new Vector3(touch.deltaPosition.x, 0, 0);
    31.                 selected.transform.position += direction * sensitivity / 200;
    32.                 selected.transform.position = new Vector3(Mathf.Clamp(selected.transform.position.x, -1.5f, 0), 0, 0);
    33.             }
    34.         }
    35.     }
    36. }
    37.  
    I hope I described the problem well.
    Thank you :)
     
  2. adi7b9

    adi7b9

    Joined:
    Feb 22, 2015
    Posts:
    181
    Code (CSharp):
    1. //try to use
    2. Vector3 direction = Vector3.forward;
     
  3. lordconstant

    lordconstant

    Joined:
    Jul 4, 2013
    Posts:
    389
    Similar to adi's answer:

    Code (CSharp):
    1. //This will give you the right vector of the camera object
    2. Vector3 direction = Camera.main.transform.right;
    3. //You may want to also get rid of the y value to keep it flat
    4. direction.y = 0.0f;
    5. direction.Normalize();