[unity] 드래그하면 옆으로만 왔다갔다하는 큐브

드래곤 플라이트처럼 옆으로만 왔다갔다하는 큐브를 만들어보자

 

스크린샷 2014-08-08 오전 9.55.23

일단 이렇게 카메라의 아래쪽 부분에 큐브를 넣는다.

 

c# 스크립트를 만들어서 큐브에 넣어준다.

public class PlayerMove : MonoBehaviour 
{
  Transform cachedTransform;
  Vector2 startingPos;
  float moveSpeed = 0.03f;

  void Start () 
  {
    cachedTransform  = transform;
    startingPos = cachedTransform.position;
  }

  void Update () 
  {
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
    {
      float dist = transform.position.y - Camera.main.transform.position.y;
      float leftLimitation = Camera.main.ViewportToWorldPoint(new Vector3(0,0,dist)).x + gameObject.renderer.bounds.size.x * 0.5f;
      float rightLimitation = Camera.main.ViewportToWorldPoint(new Vector3(1,0,dist)).x - gameObject.renderer.bounds.size.x * 0.5f;

      Vector2 deltaPosition = Input.GetTouch(0).deltaPosition;
      cachedTransform.position = new Vector2(Mathf.Clamp((deltaPosition.x * moveSpeed) + cachedTransform.position.x, leftLimitation, rightLimitation), startingPos.y);
    }
  }
}

 

 

도움받은 곳 :

1. http://answers.unity3d.com/questions/184258/clamp-player-to-screen-borders.html

2. youtube.com/watch?v=g9p9PvnmRXU