버튼 UI 눌러서 고양이 이동하기
대리자, 람다식 사용
- 키보드입력 받아 고양이 움직이기 (주석)
Input.GetKeyDown(KeyCode.작동키)
버튼을 누르면 고양이를 좌우로 이동
transform.Translate(x,y,z)
고양이 화면밖으로 못나가게 하기
Mathf.Clamp(x, min , max )
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; //버튼 생성
public class PlayerController : MonoBehaviour
{
[SerializeField] private Button btnLeft;
[SerializeField] private Button btnRight;
public float radius=1f; //반지름 계산
private void Start()
{
//this.btnLeft.onClick.AddListener(this.LeftButtonClick); //대리자- 메소드 필요
//this.btnRight.onClick.AddListener(this.RightButtonClick);
// 람다
this.btnLeft.onClick.AddListener(() =>
{
this.transform.Translate(-2,0,0);
});
this.btnRight.onClick.AddListener(() =>
{
this.transform.Translate(2, 0, 0);
});
}
void Update()
{
//키보드 입력을 받는 코드 작성
/* if (Input.GetKeyDown(KeyCode.LeftArrow))
{
Debug.Log("왼쪽으로 2유닛만큼 이동");
//X 축으로-2만큼 이동
this.transform.Translate(-2, 0, 0);
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
Debug.Log("오른쪽으로 2유닛만큼 이동");
//X축으로 2만큼 이동
this.transform.Translate(2, 0, 0);
}*/
// 플레이어가 화면밖에 못나가게 하기
float clampX = Mathf.Clamp(this.transform.position.x, -8.13f, 8.13f);
Vector3 pos = this.transform.position;
pos.x = clampX;
this.transform.position = pos;
}
//충돌시 테두리 설정
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(this.transform.position, this.radius);
}
//대리자 메서드
/*public void LeftButtonClick()
{
//Debug.Log("왼쪽 버튼을 누르시오");
// this.transform.Translate(-2,0,0);
}
public void RightButtonClick()
{
//Debug.Log("오른쪽 버튼을 누르시오");
// this.transform.Translate(2,0,0);
}*/
}
프리팹 에셋 만들기
화살표 생성
- 화살 이동 (위 -> 아래로)
Vector3.down
화살과 고양이 충돌 판정 : 둘 사이의 거리 계산
.magnitude ;
화살이 바닥에 닿거나 고양이와 충돌하면 씬에서 제거
OnDrawGizmos() 메서드
충돌시 HP게이지 감소 설정
.FindObjectOfType<>(); 타입으로 컴포넌트 호출
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ArrowController : MonoBehaviour
{
[SerializeField] private float speed = 1f;
[SerializeField] private float radius = 1f;
//동적으로 생성되는 애는 씬에 있는거 Assign 할수 없다
private CatEscapeGameDirector gameDirector;
private GameObject playerGo;
private void Start()
{
//이름으로 게임오브젝트를 찾는다
this.playerGo = GameObject.Find("player");
//타입으로 컴포넌트를 찾는다
this.gameDirector = GameObject.FindObjectOfType<CatEscapeGameDirector>();
}
void Update()
{
//방향 * 속도 * 시간
Vector3 movement = Vector3.down * speed * Time.deltaTime;
this.transform.Translate(movement);
//Debug.LogFormat("y : {0}", this.transform.position.y);
//현재 y 좌표가 2.93보다 작아졌을때 씬에서 제거한다
if (this.transform.position.y <= -2.93f)
{
//Debug.LogError("제거!");
//Destroy(this); // ArrowController 컴포넌트가 제거 된다
Destroy(this.gameObject); //게임오브젝트를 씬에서 제거
}
//거리
Vector2 p1 = this.transform.position;
Vector2 p2 = this.playerGo.transform.position;
Vector2 dir = p1 - p2;//방향
float distance = dir.magnitude; //거리
//float distance = Vector2.Distance(p1, p2);
float r1 = this.radius;
PlayerController controller = this.playerGo.GetComponent<PlayerController>();
float r2 = controller.radius;
float sumRadius = r1 + r2;
if (distance < sumRadius) //충돌함
{
Debug.LogFormat("충돌함: {0}, {1}", distance, sumRadius);
Destroy(this.gameObject); //씬에서 제거
this.gameDirector.DecreaseHp();
}
}
//이벤트 함수
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(this.transform.position, this.radius);
}
}
프리팹 생성
일정 시간마다 화살 생성하기
Object.Instantiate(GameObject);
- x축으로 랜덤하게 생성
Random.Range(min, max)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class ArrowGenerator : MonoBehaviour
{
//프리팹 에셋을 가지고 프리팹 인스턴스를 만든다
[SerializeField] private GameObject arrowPrefab;
private float delta; //경과된 시간 변수
void Update()
{
delta += Time.deltaTime; //이전 프레임과 현재 프레임 사이 시간
Debug.Log(delta);
if (delta > 3) //3초보다 크다면
{
//생성
GameObject go = UnityEngine.Object.Instantiate(this.arrowPrefab);
//위치 재 설정
float randX = UnityEngine.Random.Range(-8, 9); //-8 ~ 8
go.transform.position
= new Vector3(randX, go.transform.position.y, go.transform.position.z);
delta = 0; //경과 시간을 초기화
}
}
}
UI에 고양이의 체력을 게이지로 표시
fillAmount
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CatEscapeGameDirector : MonoBehaviour
{
[SerializeField] private Image hpGauge;
public void DecreaseHp()
{
this.hpGauge.fillAmount -= 0.1f;
}
}
'게임개발 > 게임 클라이언트 프로그래밍' 카테고리의 다른 글
c# 대리자 및 람다 (0) | 2024.01.29 |
---|---|
Mathf.Clamp (0) | 2024.01.29 |
Space.world (0) | 2024.01.29 |
표창 던지기 (1) | 2024.01.28 |
SwipeCar (0) | 2024.01.28 |