반응형
레트로의 유니티 게임 프로그래밍 에센스 예제
닷지.
1.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
public float speed = 16f;
private Rigidbody bulletRigibody;
// Start is called before the first frame update
void Start()
{
//게임오브젝트에서 리지드바디 컴포넌트를 찾아서 bulletRigibody변수 할당
this.bulletRigibody = GetComponent<Rigidbody>();
//리지드바디의 속도 = 앞쪽방향 * 이동속령
this.bulletRigibody.velocity = this.transform.forward * speed;
Destroy(this.gameObject, 3f); // 3초 뒤에 나 자신을 없애겠다.
}
private void Update()
{
}
private void OnTriggerEnter(Collider other)
{
//충돌감지
if (other.tag == "Player") {
//상대방 게임 오브젝트에서 플레이어 컨트롤러 컴포넌트 가져오기
PlayerController playerController = other.GetComponent<PlayerController>();
//상대방으로부터 PlayerController 컴포넌트 가져온느데 성공했다면,
if (playerController != null) {
//상대방 플레이어의 다이 메서도 소환
playerController.Hit();
}
}
}
}
2
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameOver : MonoBehaviour
{
public Canvas gameOver;
}
3
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class InGame : MonoBehaviour
{
public PlayerController player;
private int score;
float delta;
public UIGame uiGame;
public GameOver gameOver;
void Start()
{
}
// Update is called once per frame
void Update()
{
Score();
uiGame.score.GetComponent<Text>().text = "score " + score;
if (player.isDie == true) {
GameOver();
}
}
public void Score() {
if (player.isDie == false)
{
this.delta += Time.deltaTime;
this.score = (int)delta * 100;
}
else {
}
}
public void GameOver()
{
gameOver.gameObject.SetActive(true);
}
}
4
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIGame : MonoBehaviour
{
public Image HpUi;
public Text score;
}
5
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletSpawner : MonoBehaviour
{
public GameObject bulletPrefab; //생성할 탄알의 원본 프리팹
public float spawnRateMin = 0.5f;
public float spawnRateMax = 3f;
private Transform target; //발사할 대상
private float spawnRate; //생성주기
private float timeAfterSpawn; //스폰되고 나서 지난시간
// Start is called before the first frame update
void Start()
{
//최근 생성이후의 누적 시간을 0으로 초기화
this.timeAfterSpawn = 0;
//탄알 생성간격을 최소 생성시간과 최대 시간 사이에 랜덤값 지정
this.spawnRate = Random.Range(this.spawnRateMin, this.spawnRateMax);
//플레이어 컴포넌트를 가진 게임 오
this.target = FindObjectOfType<PlayerController>().transform;
}
// Update is called once per frame
void Update()
{
bool isDie = FindObjectOfType<PlayerController>().isDie;
if (isDie == false) {
//시간 갱신
this.timeAfterSpawn += Time.deltaTime;
// 최근생성시점부터 누적된 시간이 생성주기보다 크거나 같으면
if (this.timeAfterSpawn > this.spawnRate)
{
//누적시간 리셋
this.timeAfterSpawn = 0;
//프리팹을 현재
GameObject bullet = Instantiate(this.bulletPrefab, this.transform.position, this.transform.rotation);
//플레이어를 바라보게 생성한다.
bullet.transform.LookAt(target);
//다음번 생성 간격을 간격사이에서 랜덤하게
this.spawnRate = Random.Range(spawnRateMin, spawnRateMax);
}
}
}
}
6.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour
{
public UIGame uiGame;
public Rigidbody playerRigibody;
public float speed = 8f;
private Animation anim;
private float delta;
public bool isDie = false;
public int hp;
public int Maxhp = 90;
private float xInput;
private float zInput;
void Start()
{
this.hp = Maxhp;
this.anim = GetComponent<Animation>();
anim.Play("idle@loop");
}
void Update()
{
if (isDie == false && this.hp > 0) {
//수평축과 수직축의 입력값을 감지해서 저장
this.xInput = Input.GetAxis("Horizontal");
this.zInput = Input.GetAxis("Vertical");
Debug.LogFormat("{0} {1}", xInput, zInput);
//실제 이동속도를 입력값과 이동속력을 사용해 결정
float xSpeed = xInput * speed; //방향과 속도
float zSpeed = zInput * speed;
//Vector3 속도를 (xSpeed, 0 , zSpeed) 로 생성
Vector3 newVelocity = new Vector3(xSpeed, 0, zSpeed);
if (newVelocity != new Vector3(0, 0, 0))
{
gameObject.transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(newVelocity), 0.15f);
playerRigibody.velocity = newVelocity;
anim.Play("walk@loop");
}
else
{
anim.Play("idle@loop");
}
}
if (isDie == true) {
this.xInput = 0;
this.zInput = 0;
delta += Time.deltaTime;
}
}
public void PlayAnimation(string animName)
{
this.anim.Play(animName);
}
public void Hit()
{
this.hp -= 30;
uiGame.HpUi.GetComponent<Image>().fillAmount -= 0.335f;
if (this.hp <= 0)
{
Die();
}
else
{
this.anim.Stop();
this.PlayAnimation("damage");
}
}
public void Die()
{
if (this.isDie == false) {
this.anim.Play("die");
this.isDie = true;
this.GetComponent<Rigidbody>().isKinematic = true;
}
if (this.isDie == true && this.delta > 2.5f)
{
this.gameObject.SetActive(false);
delta = 0;
}
}
}
-------
반응형
'Unity > 엔진프로그래밍' 카테고리의 다른 글
0415_좀비슈터 단계별 테스트 _ LineRenderer (0) | 2021.04.15 |
---|---|
0415_좀비슈터 단계별 테스트 _ 자동발사 (0) | 2021.04.15 |
0415_좀비슈터 단계별 테스트 _ IK 사용하여 총에 손 달기 (0) | 2021.04.15 |
0415_좀비슈터 단계별 테스트 _ RayCast 사용 (0) | 2021.04.14 |
0413_ Button 누르고 있을 때 슬라이드, 떼었을 때 (0) | 2021.04.13 |