2D 画面のタッチ操作でPlayer(Object)の移動をする
transform.position使用
// 移動スピード
public float speed = 10;
void Update()
{
Vector2 direction = new Vector2(0, 0);
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
float x = touch.deltaPosition.x;
float y = touch.deltaPosition.y;
// 移動する向きを求める
direction = new Vector2(x, y).normalized;
}
Move(direction, speed);
}
void Move(Vector2 direction, float speed)
{
// プレイヤーの座標の取得と移動量
Vector2 pos = transform.position;
pos += direction * speed * Time.deltaTime;
// プレイヤーの新規位置とする
transform.position = pos;
}
Rigidbody2D使用
public class Player : MonoBehaviour
{
// 移動スピード
public float speed = 10;
void Update()
{
Vector2 direction = new Vector2(0, 0);
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
float x = touch.deltaPosition.x;
float y = touch.deltaPosition.y;
// 移動する向きを求める
direction = new Vector2(x, y).normalized;
}
// 移動する向きとスピード
GetComponent<Rigidbody2D>().velocity = direction * speed;
}
}