개선이 조금 필요함
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
private float moveSpeed;
private Transform tr;
private Vector2 initTouchDown;
private Vector2 initDrag;
private void Start()
{
tr = GetComponent();
moveSpeed = 0.1f;
}
private void Update()
{
PlayerMove();
}
private void PlayerMove()
{
if (Input.GetMouseButtonDown(0))
{
initTouchDown = Input.mousePosition;
}
if (Input.GetMouseButton(0))
{
initDrag = Input.mousePosition;
initDrag = (initDrag - initTouchDown).normalized;
Debug.Log("initTouchDown : " + initTouchDown + " initDrag : " + initDrag);
tr.Translate(initDrag * moveSpeed);
}
}
}
========================================================================================================================================================
약간 개선된 코드
using UnityEngine;
public class Move : MonoBehaviour
{
private float moveSpeed;
private Transform tr;
private Vector2 initTouchDown;
private Vector2 initDrag;
private void Start()
{
tr = GetComponent();
moveSpeed = 0.1f;
}
private void Update()
{
PlayerMove();
}
private void PlayerMove()
{
if (Input.GetMouseButtonDown(0))
{
initTouchDown = Input.mousePosition;
}
if (Input.GetMouseButton(0))
{
initDrag = Direction(initTouchDown, Input.mousePosition);
tr.Translate(initDrag * moveSpeed);
}
}
private Vector2 Direction(Vector2 fir, Vector2 sec)
{
if (fir.x <= sec.x + 50 && fir.x >= sec.x - 50)
{
if (fir.y <= sec.y + 50 && fir.y >= sec.y - 50)
return Vector2.zero;
else
return new Vector2(0, sec.y - fir.y).normalized;
}
else
{
if (fir.y <= sec.y + 50 && fir.y >= sec.y - 50)
return new Vector2(sec.x - fir.x, 0).normalized;
else
return (sec - fir).normalized;
}
}
}
'Unity > Unity자체' 카테고리의 다른 글
마우스 8방향 이동 (0) | 2020.03.09 |
---|