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


はじめに

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

 

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

 

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

前章
AddComponent>NewScriptを押します。そして、
すると、プロジェクトのアセットに「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. // 省略
 

「void Start()」の後に続く「{}」の中に上の通りに書き込んでください。

 

少し説明すると、

  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;