[ GameObject 드래그 : Touch(마우스) Input 처리하기 ]
클릭된 오브젝트가 마우스(터치) 드래그에 따라 움직일 수 있도록 함
[ Touch(마우스) Input 처리하기 ]
마우스 입력 처리 - Input.GetMouseXXX(0) 함수는 스마트폰의 Touch와 연계되어 있음
Input.GetMouseButtonDown(0) : 마우스가 클릭될 때 true 값을 리턴
Input.GetMouseButton(0) : 마우스가 움직이고 움직이고 있을 때 true 값을 리턴
Input.GetMouseButtonUp(0) : 마우스가 클릭을 때는 순간 true 값을 리턴
인자값으로 0이 들어가는것은 마우스 왼쪽버튼 1 오른쪽버튼2 가운데 버튼
GameObject Touch 처리
마우스 입력 위치에 GameObject(Collider)가 있는지를 검사해야 함
Ray/Racast 를 이용하여 처리하게 됨
[ 실습 ]
Hero (GameObject) 생성
Tag : Player 설정
PlayerContorls.cs를 삽입
using UnityEngine;
using System.Collections;
public class PlayerControls01 : MonoBehaviour {
void Start ()
{
}
void Update ()
{
if(Input.GetMouseButtonDown(0))
{
Debug.Log ("Mouse Down");
}
else if (Input.GetMouseButton (0))
{
Debug.Log("Mouse Move");
}
else if(Input.GetMouseButtonUp(0))
{
Debug.Log ("Mouse Up");
}
}
}
using UnityEngine;
using System.Collections;
public class PlayerControls02 : MonoBehaviour {
private Vector3 pos, oldpos;
public bool bMove = false;
private bool bPause = false;
void Start ()
{
}
void Update ()
{
if(Input.GetMouseButtonDown(0))
{
//Debug.Log ("Mouse Down");
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
Ray2D ray2D = new Ray2D(new Vector2(ray.origin.x, ray.origin.y), new Vector2(ray.direction.x, ray.direction.y));
RaycastHit2D[] hits = Physics2D.RaycastAll(ray2D.origin, ray2D.direction);
int i = 0;
while(i < hits.Length) {
RaycastHit2D hit = hits[i];
if(hit.collider.tag == "Player") {
if(!bPause) {
bMove = true;
pos = transform.position;
}
}
//Debug.Log ("Touch -> " + hit.collider.tag);
i++;
}
}
else if (Input.GetMouseButton (0))
{
if(bMove)
{
oldpos = pos;
pos = Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, Input.mousePosition.z));
transform.position = new Vector3 (transform.position.x + (pos.x - oldpos.x),
transform.position.y + (pos.y - oldpos.y),
transform.position.z);
/*
transform.localPosition = new Vector3 (transform.localPosition.x + (pos.x - oldpos.x),
transform.localPosition.y + (pos.y - oldpos.y),
transform.localPosition.z);
*/
//Debug.Log("Mouse Move");
}
}
else if(Input.GetMouseButtonUp(0))
{
//Debug.Log ("Mouse Up");
bMove = false;
}
}
}