ひつじを動かそう のバックアップ(No.6)


はじめに

Unity 初学者のすゝめの続きです。

 

「Unity 初学者のすゝめ」では重力操作や当たり判定などの簡単な物理演算による操作を勉強しました。
しかし、さらに複雑な操作をしようと思うとプログラミングでの操作が必要になります。
そのため、このページではUnity上でのC#のプログラミングの基本を勉強します。

 

ひつじをC#で動かしてみる

「Unity 初学者のすゝめ」

すると、プロジェクトのアセットに「text.cs」というのが追加されました。
これをダブルクリックします。

 
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class MoveSheep : MonoBehaviour
  6. {
  7.     // Start is called before the first frame update
  8.     void Start()
  9.     {
  10.     }
  11.  
  12.     // Update is called once per frame
  13.     void Update()
  14.     {
  15.     }
  16. }
 
  1. // 省略
  2.     void Start()
  3.     {
  4.         // ここから書いていく
  5.         Vector3 pos = this.transform.position; // このオブジェクト(ひつじ)の位置を変数として取得
  6.  
  7.         pos.x = 3; // x座標を変更
  8.         pos.y = 4; // y座標を変更
  9.  
  10.         this.transform.position = pos; // 変数を代入
  11.     }
  12. // 省略
  1. // 省略
  2.     // Start is called before the first frame update
  3.     void Start()
  4.     { 
  5. // 全部消す
  6.     }
  7.  
  8.     // Update is called once per frame
  9.     void Update()
  10.     { 
  11.         // ここから書いていく
  12.         Vector3 pos = this.transform.position; // このオブジェクト(ひつじ)の位置を変数として取得
  13.  
  14.         pos.x += 0.01f; // x座標を変更
  15.         pos.y += 0.01f; // y座標を変更
  16.  
  17.         this.transform.position = pos; // 変数を代入
  18.     }
  19. }
  1. A = A + B;
  1. A += B;
  1. // 省略
  2.     //ここに書き加える
  3.     public float speed = 0.01f; // 初期値付きで変数を定義
  4.  
  5.     // Start is called before the first frame update
  6.     void Start()
  7.     {
  8.     }
  9.  
  10.     // Update is called once per frame
  11.     void Update()
  12.     { 
  13.         Vector3 pos = this.transform.position;
  14.  
  15.         pos.x += speed; //0.01f から speed に書き換え 
  16.         pos.y += speed; //0.01f から speed に書き換え 
  17.  
  18.         this.transform.position = pos;
  19.     }
  20. }