05-17 06:36
Notice
Recent Posts
Recent Comments
관리 메뉴

Scientific Computing & Data Science

Script for Touch & Drag an Object 본문

CG & Video Games/Unity 3D

Script for Touch & Drag an Object

cinema4dr12 2013. 5. 26. 12:08

using UnityEngine;

using System.Collections;

 

public class DragObject : MonoBehaviour {

private Ray myRay = new Ray();

RaycastHit myHit = new RaycastHit();

 

[SerializeField]

    private float _horizontalLimit = 2.5f;

    private float _verticalLimit = 2.5f;

    private float dragSpeed = 0.005f;

    private Transform cachedTransform;

    private Vector3 startingPos;

 

// Use this for initialization

void Start () {

 

}

 

// Update is called once per frame

void Update () {

 

if(Input.touchCount > 0)

{

Vector2 deltaPosition = Input.GetTouch(0).deltaPosition;

 

//Switch through touch events

         switch(Input.GetTouch(0).phase)

         {

       case TouchPhase.Began:

myRay = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);

if (Physics.Raycast(myRay, out myHit, 100.0f))

cachedTransform = myHit.collider.transform;

               break;

                 case TouchPhase.Moved:

    Drag(deltaPosition);

               break;

       case TouchPhase.Ended:

               break;

         }

}

 

}

 

/// <summary>

/// Drags the object.

/// </summary>

/// <param name='deltaPosition'>

/// Delta position.

/// </param>

void Drag(Vector2 deltaPosition)

{

    cachedTransform.position = new Vector3(Mathf.Clamp((deltaPosition.x * dragSpeed) + cachedTransform.position.x,

startingPos.x - _horizontalLimit, startingPos.x + _horizontalLimit),

Mathf.Clamp((deltaPosition.y * dragSpeed) + cachedTransform.position.y,

startingPos.y - _verticalLimit, startingPos.y + _verticalLimit),

cachedTransform.position.z);

}

}

'CG & Video Games > Unity 3D' 카테고리의 다른 글

Sending Commands Using RPC  (0) 2013.05.26
Script for Network Instantiate(JS)  (0) 2013.05.26
Dynamic Images  (0) 2013.05.26
VertextLit Shader  (0) 2013.05.26
Display Normal Shader  (0) 2013.05.26
Comments