LoginSignup
0
0

Unityでのゲーム作り日記#7 ~ユニットをつくる~

Last updated at Posted at 2024-01-23

前回の記事はこちら

今回は、ユニットを作っていきます。
ユニットとは、シミュレーションゲームなどである、動かすことのできるキャラクターっぽいやつのことです。
多分、この記事は何度も修正されると思います。

Unitを作る

CodeFight2.png スクリーンショット 2024-01-21 083548.png
こんな感じのやつを作ります。適当に四角形を組み合わせて作りました。
ちなみに、青い部分を白い部分の子にしておいたほうが後で楽になると思います。
あと、プレファブ化もしておきます。

Unitオブジェクトに、下のプログラムをドラッグしてください。

UnitScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UnitScript : MonoBehaviour
{
   public double speed;
   public double angle;
   public Interpreter interpreter;

   public static nowId = 0; //ユニットの番号を決めるのに使う

   // Start is called before the first frame update
   void Start()
   {
       Interpreter interpreter = new TurquoiseInterpreter(nowId); //番号を与える
       gameObject.name = "Unit" + nowId;
       nowId++;
       
       angle = 0.0;
   }

   // Update is called once per frame
   void Update()
   {
       Vector3 rotate = transform.eulerAngles;
       rotate.z = (float)angle;
       transform.eulerAngles = rotate;

       transform.position += transform.right * -(float)speed; //二次元では前はrightの反対
   }

   public void Rotate(double addAngle)
   {
       angle += addAngle;
   }
}

interpreterは後々使います。(多分)

自作言語からUnitの回転ができるようにする

ネイティブ関数にRotateを追加します。(以後、ネイティブ関数の名前は、ユニットの操作に関係がなければ小文字から、関係があれば大文字から始めます。)

構文木を表すクラスの変更

まず、すべてのEvaluateメソッドがunitIdという引数を取るようにします。
インターフェイスやEvaluateメソッドの呼び出しの部分も変更します。
Evaluateメソッドの中で呼ばれたEvaluateメソッドには同じunitIdを渡します。
プログラムは割愛します。

インタープリタの変更

コンストラクタでUnitの番号を受け取り、executeメソッドの中のEvaluateメソッドを呼ぶときにunitIdとして渡します。
ここでもプログラムは割愛します。

NaitiveProcessにRotateの処理を追加

NaitiveProcessクラスのEvaluateメソッドのswitch文にしたのコードを追加します。

case "Rotate":
   {
       Value rotateValue = Environments.getVarValue(_argmentNames[0]);

       UnitScript unitScript = GameObject.Find("Unit").GetComponent<UnitScript>(); //後々修正していきます
       unitScript.Rotate(rotateValue.getDouble()); //回転させる
       
       return rotateValue;
   }

次に、Environmentsクラスのコンストラクタのprint関数の追加処理の下にしたのコードを追加します。

ParameterExpression RotateParameter = new ParameterExpression(new IExpression[] { new VariableExpression("n") });
NativeProcess RotateProcess = new NativeProcess("Rotate", new string[] { "n" });
firstEnvironment.addFuncNameAndValue("Rotate", new FunctionsNameAndValue(new FunctionExpression("Rotate", RotateParameter), RotateProcess));

動かしてみる

Unitが動いている途中にRotate(90)とかを実行すると回転してくれるようになります。
ちなみに、私はUnitが場外に出ていかないように当たり判定を付けた壁を作りました。

最後に

次回はユニットを作るジェネレータを作っていきます。
次回の記事はこちら

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0