タンク用 コード
このコードをタンクに設定すると「タンクがクリックで動き」「ボタンを離すと球を打ち出す」ようになります。
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class Tank : MonoBehaviour {
GameObject goshell = null;
bool action = false;
public Rigidbody2D rb;
// ゲームを起動したときに最初に実行される部分
void Start () {
goshell = transform.FindChild("tama").gameObject;
// 砲弾を非表示
goshell.SetActive(false);
rb = GetComponent<Rigidbody2D>();
}
// 1秒間に30回、または60回処理される
void Update () {
// マウスがクリックされたかどうかの判定
if (Input.GetMouseButton(0))
{
// マウスの位置を取得するプログラム
Vector2 tapPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Collider2D collition2d = Physics2D.OverlapPoint(tapPoint);
if (collition2d)
{
// タンクをクリックしたかどうかの判定
if(collition2d.gameObject == gameObject)
{
action = true;
}
}
if (action)
{
// 戦車の移動プログラム 右に15、上に0移動する
rb.AddForce(new Vector2(+15.0f, 0.0f));
}
}
else
{
// マウスが離されて、かつタンクをクリックしていたときの処理
if(Input.GetMouseButtonUp(0) && action)
{
if (goshell)
{
// 砲弾を表示する
goshell.SetActive(true);
// 砲弾を飛ばす 右に300、上に500
goshell.GetComponent<Rigidbody2D>().AddForce(new Vector2(+300.0f, +500.0f));
// 3秒後に砲弾が消える
Destroy(goshell.gameObject, 3.0f);
}
action = false;
}
}
}
// ボタンを表示するプログラム
void OnGUI()
{
// 左上から右に10、下に10の位置に 横幅100、縦幅20の大きさのボタンを作る
if(GUI.Button(new Rect(10, 10, 100, 20), "リセット"))
{
// リセットボタンを押すともう一度ゲームを始める処理をする
string sceneName = SceneManager.GetActiveScene().name;
SceneManager.LoadScene(sceneName);
}
}
}
コア用(吹き飛ぶ)コード
このコードを吹き飛ばしたい(サンプルではロボットの体に設定)ところに設定すると「物が当たったら吹き飛ぶ」ようになります。
using UnityEngine;
using System.Collections;
public class Core : MonoBehaviour {
Rigidbody2D rb;
// ゲームを起動したときに最初に実行される部分
void Start () {
rb = GetComponent<Rigidbody2D>();
}
// 1秒間に30回、または60回処理される
void Update () {
}
void OnCollisionEnter2D(Collision2D col)
{
// 砲弾がコアと接触したかどうかの判定
if(col.gameObject.name == "tama")
{
// コアが右に1000、上に300で吹き飛ぶ
rb.AddForce(new Vector2(1000.0f, 300.0f));
}
}
}
おまけ:スペースキーを押したら砲弾を飛ばす
どこに入れればうまく動くかは色々と試してみてね!
//キーボード入力処理
(スペースキーが押されたとき)
if(Input.GetKeyDown(KeyCode.Space)){
goshell.SetActive(true);
//砲弾の発射速度
goshell.GetComponent().AddForce(new Vector2(+300.0f, +500.0f));
Destroy(goshell.gameObject, 3.0f);
}








