最近工作中的新需求,手指触摸屏幕选中物体跟随手指移动的任务,开发完成后便记录下来,大家共勉

public class TouchTest : MonoBehaviour
{
    public Transform currTouchObj;
    private Camera mainCamera;
    private void Awake()
    {
        mainCamera = Camera.main;
    }

    public void CtrlTouchObjMove()
    {
 		if (Input.touchCount == 1)
        {
            Touch firstTouch = Input.GetTouch(0);
            if (firstTouch.phase == TouchPhase.Began)
            {
                Ray ray = mainCamera.ScreenPointToRay(firstTouch.position);
                RaycastHit hit;
                if (Physics.Raycast(ray, out hit))
                {
                		//获取当前触摸到的物体
                        currTouchObj = hit.collider.transform;
                }
            }

            if (Input.GetTouch(0).phase == TouchPhase.Moved)
            {     
                if (currTouchObj)
                {
                    Vector3 touchDeltaPos = Input.GetTouch(0).deltaPosition;
                    currTouchObj.Translate(touchDeltaPos.x * touchObjMoveSpeed, touchDeltaPos.y * touchObjMoveSpeed, 0, Space.World);
                }
            }
	}
}

更多推荐