Shooting Game チュートリアル 第03回
すすめていきます。
3.1 プレイヤーの弾を作成する
問題なし。
3.2 プレイヤーの弾を動かす
空のGameObjectをまるでフォルダのように。
そしてスクリプトを書いて、、あ、これはエラー出るパターン。
前回と同じように書きなおす。
using UnityEngine;
using System.Collections;
public class Bullet : MonoBehaviour {
public int speed = 10;
private Rigidbody2D rb2;
void Start () {
rb2 = GetComponent<Rigidbody2D>();
rb2.velocity = transform.up.normalized * speed;
}
}
そしてプレハブ更新。
3.3 プレイヤーから弾を発射する
あ、ここでコルーチンが出てきていたのね。
これでは動かなくて。
IEnumerator Start ()
{
rb2 = GetComponent<Rigidbody2D>();
while (true) {
Instantiate (bullet, transform.position, transform.rotation);
yield return new WaitForSeconds (0.05f);
}
}
なんやかんやと前回同様こちらを参考にさせていただきました。
っていうかもうほぼ写してます。ありがとうございます。
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float speed = 5;
public GameObject bullet;
private Rigidbody2D rb2;
private Transform bulletTransform;
void Start() {
rb2 = GetComponent<Rigidbody2D>();//取得
StartCoroutine ("FirstCoroutine");
}
IEnumerator FirstCoroutine ()
{
while (true) {
bulletTransform = GetComponent<Transform>();
Instantiate (bullet, bulletTransform.position, bulletTransform.rotation);
yield return new WaitForSeconds (0.05f);
}
}
void Update () {
float x = Input.GetAxisRaw("Horizontal");
float y = Input.GetAxisRaw("Vertical");
Vector2 direction = new Vector2(x, y).normalized;
rb2.velocity = direction * speed;//使用
}
}
無事動きました。
3.4 スプライトの描画順
で、超いまさらなんですけどBulletの位置、チュートリアルのまま(x=0.14,-0,14)だとちょっとずれてるので0.07と-0.07に直しました。
そんでレイヤーも直してOK。
次回に続きます。