背景
シューティングゲームを作っていて、スワイプで自機を移動させたかったので実現方法をメモ
前提
物体を移動させるには下記の2種類の方法があるが、今回はrigidbodyを使うやり方でやってみた。
- transform.position(座標)を上書きする方法
- rigidbodyを使ってrigidbody.velocityに速度ベクトルを代入する方法
コード
PlayerController.cs
void Update()
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved) {
deltaPosition = Input.GetTouch(0).deltaPosition / 100; // 100で割ってるのは割らないと移動距離が長くなりすぎるので小さくするため
rigidbody.velocity = new Vector3(deltaPosition.x, 0f, deltaPosition.y) * speed;
}
備考
unity超初心者なので変な箇所あったら教えてほしいです。