유니티에서 탱크 모델을 제어하는 예
사용된 탱크 모델: http://tf3dm.com/download-page.php?url=abrams-tank-17774
사용된 사운드 파일
[방향키로 포탑과 포신을 작동하고 스페이스키로 포탄을 발사하며 숫자키 패드의 방향키로 이동, 회전도 가능함]
Tank.cs
using UnityEngine;
using System.Collections;
public class Tank : MonoBehaviour {
public GameObject ballPrefab; // 포탄 프리팹
private GameObject ballPoint; // 발사할 포탄의 초기위치를 참조할 목적으로 포신의 끝에 포함한 EmptyObject
private GameObject mainTurret; // 탱크의 포탑 오브젝트(Hierarchy 뷰에서 마우스로 선택하여 Scene뷰에서 확인됨)
private GameObject mainBarrel; // 탱크의 포신
// Use this for initialization
void Start () {
ballPoint = GameObject.Find("BallPoint");
mainTurret = GameObject.Find ("Main_Turret");
mainBarrel = GameObject.Find ("Main_Barrel");
}
/**
* Tank
* |- Main_Turret(포탑)
* |- Main_Barrel(포신)
* |- BallPoint(EmptyObject, 복제된 포탄 인스턴스의 초기위치를 참조할 목적으로 추가함)
*/
// Update is called once per frame
void Update () {
if(Input.GetButtonDown("CannonBall")) { // 스페이스 키
//포신이 향하고 있는 방향을 구한다
// Quaternion은 회전정보이며 벡터와 곱하면 해당벡터를 회전변환한 결과 벡터가 산출된다
Vector3 dir = mainBarrel.transform.rotation * Vector3.forward;
// 프리팹 원본 오브젝트를 이용하여 인스턴스를 생성한다
GameObject ball = (GameObject)Instantiate(ballPrefab, ballPoint.transform.position, Quaternion.identity);
Rigidbody rb = ball.AddComponent<Rigidbody>();
// 포신이 향한 방향과 각도를 향하여 포탄 발사
print ("발사");
rb.AddForce(dir*2000f);
}
// 좌우 방향키에 따라서 포탑을 좌우로 회전한다
mainTurret.transform.Rotate(mainTurret.transform.up * Input.GetAxis("Horizontal"), Space.World);
// 상하 방향키에 따라서 포신의 상하 각도를 변경한다
mainBarrel.transform.RotateAround(mainTurret.transform.position, mainBarrel.transform.right,Input.GetAxis ("Vertical"));
}
void FixedUpdate() {
Move ();
}
void Move() {
//print ("Move");
Rigidbody rb = gameObject.GetComponent<Rigidbody> ();
if(Input.GetKey(KeyCode.Keypad8)) {
print ("전진");
rb.AddForce (transform.forward * 7f);
}
if(Input.GetKey(KeyCode.Keypad6)){
print("우회전");
transform.Rotate (new Vector3(0F,1F,0F)*Time.fixedDeltaTime*20f);
}
if(Input.GetKey(KeyCode.Keypad4)){
print("좌회전");
transform.Rotate (new Vector3(0F,1F,0F)* -Time.fixedDeltaTime*20f);
}
if(Input.GetKey(KeyCode.Keypad2)){
print("후진");
rb.AddForce (transform.forward * -7f);
}
}
}
Ball.cs [탱크가 발사하는 포탄, Sphere를 Prefab으로 등록하고 Prefab 에 아래의 코드를 콤포넌트로 추가함]
using UnityEngine;
using System.Collections;
public class Ball : MonoBehaviour {
public GameObject explosionPrefab; // Small Explosion 프리팹을 편집하여 사용한 폭발 프리팹
public GameObject explosionSndPrefab; // 폭발 사운드 파일을 포함한 GameObject를 프리팹으로 등록한 것
private GameObject expSoundObj; // 포탄이 폭발할 때 동적으로 생성되는 사운드 프리팹의 인스턴스
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter(Collision collision) {
ContactPoint contact = collision.contacts[0];
Quaternion rot = Quaternion.FromToRotation(Vector3.up, contact.normal);
Vector3 pos = contact.point;
Instantiate (explosionPrefab, pos, rot);
expSoundObj = (GameObject)Instantiate (explosionSndPrefab, pos, rot);
Invoke ("DestroySound", 2f); // 2초 후에 DestroySound()가 호출되어 포탄, 사운드 오브젝트를 제거함
}
void DestroySound() {
Destroy (expSoundObj);
Destroy (gameObject);
}
}