본문 바로가기

Unity3D Tank/Fire

Turret Rotation & Fire

유니티 Quaternion 활용 회전 예


Cube, Sphere, Cylinder 등을 이용하여 태크 모양을 만들고 좌우 방향키를 사용하여 포탑을 회전하고, 상하 방향키를 이용하여 포신의 상하각도를 조절한 후에 스페이스 바를 누르면 포탄이 날아가는 내용



using UnityEngine;

using System.Collections;


public class Cannon : MonoBehaviour {


public GameObject ballPrefab; // 포탄 프리팹 (Sphere)


// Use this for initialization

void Start () {

}


/** Hierarchy 뷰의 오브젝트 계층구조

* Cannon(Cube, 탱크바디)

*   |- Top(Cube, 포탑)

*       |- Barrel(Cylinder, 포신)

*            |- BallPoint(EmptyObject, 복제된 포탄 인스턴스의 초기위치를 참조할 목적으로 추가함)

*/

// Update is called once per frame

void Update () {

if(Input.GetButtonDown("CannonBall")) { // 스페이스 키 가상버튼


GameObject ballPoint = GameObject.Find("BallPoint");

GameObject top = GameObject.Find ("Top");

GameObject ba = GameObject.Find ("Barrel");


// 프리팹 원본 오브젝트를 이용하여 인스턴스를 생성한다

GameObject ball = (GameObject)Instantiate(ballPrefab, ballPoint.transform.position, ballPoint.transform.rotation);

Rigidbody rb =  ball.GetComponent<Rigidbody>();


//포신이 향하고 있는 방향을 구한다

// Quaternion은 회전정보이며 벡터와 곱하면 해당벡터를 회전변환한 결과 벡터가 산출된다

// 아래의 rotation 속성은 Quaternion 형 참조변수이다

Vector3 dir = ba.transform.rotation * Vector3.up; // 실린더로 포신을 만들 때 90도 돌려서 up 벡터가 전방을 향하고 있음


// 포신이 향한 방향과 각도를 향하여 포탄 발사

rb.AddForce(dir*2000f);

}

GameObject cannonTop = GameObject.Find("Top");

// 좌우 방향키에 따라서 포탑을 좌우로 회전한다

cannonTop.transform.Rotate(cannonTop.transform.up * Input.GetAxis("Horizontal"));


GameObject barrel = GameObject.Find ("Barrel");

// 상하 방향키에 따라서 포신의 상하 각도를 변경한다

barrel.transform.RotateAround(cannonTop.transform.position, barrel.transform.forward,Input.GetAxis ("Vertical")*-1f);

}

}