どうも、萬朶櫻(@wanduoying)、183朶目の記事です。
前囘まででマップやオブジェクトの生成をやりました。

今囘は生成したキャラクターを動かす處理をやりたいと思ひます。
プレイヤーキャラを動かす
このキャラを動かしていきます。假のデザインなので、今後見た目が變はるかも。
白い棒みたいなのは向きを確認するためのものです。
スクリプトPlayerController.csを作成し、Update函數に記述をしてプレイヤーのプレハブにアタッチします。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { void Update () { if (Input.GetKeyDown(KeyCode.LeftArrow)) //左 { this.transform.Translate(-1, 0, 0, Space.World); } if (Input.GetKeyDown(KeyCode.RightArrow)) //右 { this.transform.Translate(1, 0, 0, Space.World); } if (Input.GetKeyDown(KeyCode.UpArrow)) //上 { this.transform.Translate(0, 0, 1, Space.World); } if (Input.GetKeyDown(KeyCode.DownArrow)) //下 { this.transform.Translate(0, 0, -1, Space.World); } } } |
とりあへずこれでマス目に沿つて動いてくれます。
斜め移動に對應してないけど、現状ではいいでせう。
しかし、これではキャラクターが常に正面を向いてゐることになり、攻撃などの處理に支障がありさうです。
なので囘轉の處理を入れていきます。
1 2 3 4 5 |
if (Input.GetKeyDown(KeyCode.LeftArrow)) //左 { this.transform.Translate(-1, 0, 0, Space.World); this.transform.Rotate(0, 90, 0, Space.World); } |
最初はこのやうに、矢印キーを押したら囘轉、と云ふ風にやつてみたんですが、これではプレイヤーが移動ごとに餘計な囘轉をするのでダメみたいです。

左に動く場合。赤色矢印はキャラの向き。
そこでTech Academyにて相談してみたら良い解決法を教へてもらひました。
1 2 3 4 5 |
if (Input.GetKeyDown(KeyCode.LeftArrow)) //左 { this.transform.Translate(-1, 0, 0, Space.World); this.transform.rotation = Quaternion.Euler(0.0f, 90.0f, 0.0f); } |
Quaternion.Euler()といふのを使へば直接向きを代入できるらしいです。
敵の移動
とりあへず假といふことで、ランダム移動させてゐます。
EnemyController.csを作り、敵のプレハブにアタッチします。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyController : MonoBehaviour { public void EnemyMove() { int numX = Random.Range(-1, 2); int numY = Random.Range(-1, 2); //移動 this.transform.Translate(numX, 0, numY, Space.World); //移動方向に應じて向きを變へる if (0 < numX) { this.transform.rotation = Quaternion.Euler(0.0f, -90.0f, 0.0f); } else if (numX < 0) { this.transform.rotation = Quaternion.Euler(0.0f, 90.0f, 0.0f); } else if (0 < numY) { this.transform.rotation = Quaternion.Euler(0.0f, -180.0f, 0.0f); } else if (numY < 0) { this.transform.rotation = Quaternion.Euler(0.0f, 180.0f, 0.0f); } } |
Update()に書いてしまふと1フレーム毎に高速移動してしまひます。EnemyMove()を作つてそこに書きました。
今のところ、この函數を呼び出すための記述をしてゐないので、實行しても敵は動きません。
現状はここまで。
今後はプレイヤーと敵が交互に動くターン制を實裝したいと思ひます。
コメントを残す