본문 바로가기
유니티강좌

스마트폰 화면 터치시 오브젝트 위치 이동 | Touch And Move Object | - 유니티 2D게임 개발(Unity & C#) 튜토리얼

by Ncube 2020. 12. 25.

 

 

안드로이드 스마트폰 화면을 터치했을때, 오브젝트가 터치한 위치로 이동하는 방법. apk파일 설치후 AndroidPhone 테스트. GetTouch, TouchPhase.Began.

 

#스마트폰터치시위치이동  #GetTouch  #TouchPhase.Began

 

 

[TouchMove.cs]

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TouchMove : MonoBehaviour
{
    Rigidbody2D rb;
    [SerializeField] float speed = 500f;

    Touch touch;
    Vector3 touchPos, moveDir;
    float previousTouch, currentTouch;

    bool isMoving = false;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (isMoving)
            currentTouch = (touchPos - transform.position).magnitude;

        if (Input.touchCount > 0)
        {
            touch = Input.GetTouch(0);

            if(touch.phase == TouchPhase.Began)
            {
                previousTouch = 0;
                currentTouch = 0;
                isMoving = true;
                touchPos = Camera.main.ScreenToWorldPoint(touch.position);
                touchPos.z = 0;
                moveDir = (touchPos - transform.position).normalized;
                rb.velocity = new Vector2(moveDir.x * speed * Time.deltaTime, 
                    moveDir.y * speed * Time.deltaTime);
            }

        }

        if(currentTouch > previousTouch)
        {
            isMoving = false;
            rb.velocity = Vector2.zero;
        }

        if (isMoving)
            previousTouch = (touchPos - transform.position).magnitude;
    }
}

 

댓글