상세 컨텐츠

본문 제목

Unity mouse Drag object/ Touch moved

개발생활/Unity Engine

by 한국인맛집 2019. 1. 15. 15:56

본문

반응형


Unity 3D  Drag Move Object 




  • Mouse moved.
public class DragScript : MonoBehaviour{

public GameObject player;


void Update(){

if(Input.GetMouseButton(0)) {
            float distanceToScreen = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;

            Vector3 posMove = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,
                                                      Input.mousePosition.y, distanceToScreen));


            float nextX = player.transform.position.x + posMove.x;

            Debug.Log(nextX);

            Debug.Log("player: "+player.transform.position.x);

            if(nextX <= 5.0 && nextX >= -5.0) {
                player.transform.position = new Vector3(posMove.x, transform.position.y, 0);

            } // Object Move Limited Android Screen
         }
     }
}


  • SmartPhone Touch moved
public class DragScript : MonoBehaviour{

public GameObject player;


void Update(){

 if(Input.touchCount != 0) {

            Touch t = Input.GetTouch(0);


            if(t.phase == TouchPhase.Moved) {
                float distanceToScreen = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
                Vector3 posMove = Camera.main.ScreenToWorldPoint(
                                     new Vector3(t.position.x, t.position.y, distanceToScreen));


                float nextX = player.transform.position.x + posMove.x;

               
                if(nextX <= 5.0 && nextX >= -5.0) {
                    player.transform.position = new Vector3(posMove.x, transform.position.y, 0);

                }
            }

            
         
        }
     }
}

반응형

관련글 더보기