728x90
exp/돈 오르기 ->UI에 적용하기 (근데 초기값이 잘 안ㄴ뜸..?;;) 0이라고 뜸 1인데 ㅡ;
GameManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public int Stage;
public int Level;
public int exp;
public int hp;
public int money;
//public int money;
public static GameManager instance;
PlayerMove player;
public bool isEnterSaveJone=false;
public Text Money_Text;
public Text Level_Text;
private void Start() {
player= GetComponent<PlayerMove>();
instance = this;
Level = player.Level;
money = player.money;
}
private void Awake() {
Level_Text.text="Lv."+Level.ToString();
Money_Text.text = money.ToString();
}
public void LevelUp(int level){
Level_Text.text="Lv."+level.ToString();
}
public void GetMoney(int money){
Money_Text.text=money.ToString();
}
}
PlayerMove.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
public int maxHP;
public int hp;
public int Attack_Range;//다음 행동지표를 결정할 변수
public int Level;
public int exp;
public int op;
public int money;
public MonsterMove monster;
bool isDie = false;
public float maxSpeed;
public float jumpPower;
public int direction;
Rigidbody2D rigid;
SpriteRenderer spriteRenderer;
Animator anim;
// Start is called before the first frame update
void Start(){
Level=1;
maxHP = 100 + Level*25;
hp = maxHP;
Attack_Range = 5;
direction = 1;
op= 10 + Level*2;
}
void Awake()
{
rigid = GetComponent<Rigidbody2D>();
spriteRenderer = GetComponent<SpriteRenderer>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
//점프
if (Input.GetButton("Jump") && !anim.GetBool("isJump"))
{
rigid.AddForce(Vector2.up * jumpPower, ForceMode2D.Impulse);
anim.SetBool("isJump", true);
}
//멈추기
if (Input.GetButtonUp("Horizontal"))
{
rigid.velocity = new Vector2(rigid.velocity.normalized.x * 0.5f, rigid.velocity.y);
}
//방향 전환
if (Input.GetButton("Horizontal"))
{
if(Input.GetAxisRaw("Horizontal") == -1){
direction = -1;
spriteRenderer.flipX = Input.GetAxisRaw("Horizontal") == -1;
Debug.Log(direction);
}
else{
spriteRenderer.flipX = Input.GetAxisRaw("Horizontal") == -1;
direction = 1;
Debug.Log(direction);
}
}
//공격
if (Input.GetButtonDown("Attack"))
{
//애니메이션 실행
anim.SetTrigger("isAttack");
//몬스터를 감지하는 레이를 발사
Vector2 detect_mon = new Vector2(rigid.position.x, rigid.position.y-2.5f);
Debug.DrawRay(detect_mon , new Vector3(direction*Attack_Range,0,0), Color.blue); //빔을 쏨
//감지되는 몬스터 레이어를 저장
RaycastHit2D raycast_monster = Physics2D.Raycast(detect_mon, new Vector3(direction,0,0),Attack_Range,LayerMask.GetMask("Monster"));
//null이 아닐경우 : 무언가 공격에 닿음
if(raycast_monster.collider != null){
Debug.Log(raycast_monster.collider.name);
//애니메이션이 실행되는 동안
if(anim.GetCurrentAnimatorStateInfo(0).IsName("Player_Attack")){
//레이에 닿은 몬스터를 공격
OnAttack(raycast_monster.transform);
}
}
}
//애니메이션
if (Mathf.Abs(rigid.velocity.x) < 0.3)
anim.SetBool("isRun", false);
else
anim.SetBool("isRun", true);
//생명
if(hp==0){
if(!isDie)
Die();
return;
}
}
void FixedUpdate()
{
//점프
if (Input.GetButton("Jump") && !anim.GetBool("isJump"))
{
rigid.AddForce(Vector2.up * jumpPower, ForceMode2D.Impulse);
anim.SetBool("isJump", true);
}
float h = Input.GetAxisRaw("Horizontal");
Move();
Jump();
//덩쿨 올라가기
Vector2 frontVec = new Vector2(rigid.position.x, rigid.position.y);
Debug.DrawRay(frontVec, Vector3.right * 1, new Color(0, 1, 0));
RaycastHit2D raycast = Physics2D.Raycast(frontVec, Vector3.right, 0.1f, LayerMask.GetMask("Structure"));
if (raycast.collider != null)
{
anim.SetBool("isHanging", true);
if (Input.GetButtonDown("Jump"))
{
//덩쿨에서 점프하면 빠져나오는 부분
rigid.constraints = RigidbodyConstraints2D.None | RigidbodyConstraints2D.FreezeRotation;
transform.position = new Vector2(transform.position.x + h * 2, transform.position.y);
rigid.AddForce(Vector2.up * jumpPower, ForceMode2D.Impulse);
anim.SetBool("isHanging", false);
anim.SetBool("isJump", true);
Jump();
}
else
{
//덩쿨 올라가는 부분
rigid.constraints = RigidbodyConstraints2D.FreezePositionX | RigidbodyConstraints2D.FreezePositionY;
if (Input.GetButton("Vertical"))
{
rigid.constraints = RigidbodyConstraints2D.None | RigidbodyConstraints2D.FreezeRotation | RigidbodyConstraints2D.FreezePositionX;
float updown = Input.GetAxisRaw("Vertical");
rigid.AddForce(Vector2.up * updown * 10, ForceMode2D.Impulse);
}
}
}
else
{
anim.SetBool("isHanging", false);
}
}
private void OnCollisionEnter2D(Collision2D other){
//x를 누르고 있을 때 충돌시??
//if(other.gameObject.tag == "Monster"){
// if(anim.GetCurrentAnimatorStateInfo(0).IsName("Player_Attack")){
// OnAttack(other.transform);
// }
//Obstacle 콜라이더 때문에 충돌이밴트 못생겨서 타일맵으로 다시찍어야함
// else{
// OnDamaged(other.transform.position);
// }
//}
if(other.gameObject.tag == "Monster" || other.gameObject.tag == "Obstacle"){
OnDamaged(other.transform.position);
//부딪힌 오브젝트(몬스터)의 스크립트 가져오기
monster=other.gameObject.GetComponent<MonsterMove>();
hp = hp - monster.op;
}
//else if(other.gameObject.tag == "Obstacle"){
// OnDamaged(other.transform.position); //현재 충돌한 오브젝트의 위치값을 넘겨줌
//}
}
void OnDamaged(Vector2 tartgetPos){
gameObject.layer = 12; //playerDamaged Layer number가 12로 지정되어있음
//깜박이는 함수를 불러오기
StartCoroutine("Blinking");
//맞으면 튕겨나가는 모션
int dirc = transform.position.x-tartgetPos.x > 0 ? 1 : -1;
//튕겨나가는 방향지정 -> 플레이어 위치(x) - 충돌한 오브젝트위치(x) > 0: 플레이어가 오브젝트를 기준으로 어디에 있었는지 판별
//> 0이면 1(오른쪽으로 튕김) , <=0 이면 -1 (왼쪽으로 튕김)
rigid.AddForce(new Vector2(dirc,1)*20, ForceMode2D.Impulse); // *7은 튕겨나가는 강도를 의미
Invoke("OffDamaged",2); //2초의 딜레이 (무적시간 2초)
}
//깜빡이는함수
IEnumerator Blinking(){
//Debug.Log("Blink");
int countTime=0;
while(countTime<10){
if(countTime%2==0){
spriteRenderer.color = new Color(1,1,1,0.4f);
}
else{
spriteRenderer.color = new Color(1,1,1,0.7f);
}
yield return new WaitForSeconds(0.3f);
countTime++;
}
spriteRenderer.color = new Color(1,1,1,1);
yield return null;
}
void OnAttack(Transform enemy){
MonsterMove enemyMove = enemy.GetComponent<MonsterMove>();
enemyMove.OnDamaged(op);
if(enemyMove.hp<0){
money += enemyMove.money_result();
exp += enemyMove.exp_result();
if(exp>=100)
Level=LevelUp(exp);
GameManager.instance.GetMoney(money);
}
}
public int LevelUp(int exp){
exp= exp-100;
Level++;
GameManager.instance.LevelUp(Level);
return Level;
}
void OffDamaged(){ //무적해제함수
gameObject.layer = 8; //플레이어 레이어로 복귀함
spriteRenderer.color = new Color(1,1,1,1); //투명도를 1로 다시 되돌림
}
void Move()
{
//이동
float h = Input.GetAxisRaw("Horizontal");
rigid.AddForce(Vector2.right * h * 3, ForceMode2D.Impulse);
//최대 속력
if (rigid.velocity.x > maxSpeed) //Right Max Speed velocity : 리지드바디의 현재 속도
{
rigid.velocity = new Vector2(maxSpeed, rigid.velocity.y);
}
else if (rigid.velocity.x < maxSpeed * (-1)) //Left Max Speed
{
rigid.velocity = new Vector2(maxSpeed * (-1), rigid.velocity.y);
}
}
void Jump()
{
//점프 판단 위한 빔쏘기
if (rigid.velocity.y < 0)
{
Debug.DrawRay(rigid.position, Vector3.down * 4.7f, new Color(0, 1, 0)); //빔을 쏨
RaycastHit2D rayHit = Physics2D.Raycast(rigid.position, Vector3.down, 4.7f, LayerMask.GetMask("Platform"));
//Debug.Log(rayHit.collider.name);
if (rayHit.collider != null) //빔에 맞는 내용물이 있을 때
{
//Debug.Log(rayHit.collider.name);
//if (rayHit.distance < 4f)
anim.SetBool("isJump", false);
}
}
}
void Die(){
isDie = true;
rigid.velocity = Vector2.zero;
}
}
바닥 닿앗을때 재생성 없음
몬스터 공격력만큼 공격당하기 / 덩쿨 오르기
MonsterMove.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonsterMove : MonoBehaviour
{
public float hp;
public int op;
public int given_exp;
public int given_money;
public int nextMove;//다음 행동지표를 결정할 변수
// Start is called before the first frame update
Rigidbody2D rigid;
SpriteRenderer spriteRenderer;
CapsuleCollider2D capcollider;
PlayerMove player;
// Start is called before the first frame update
void Start(){
}
private void Awake() {
player = GetComponent<PlayerMove>();
rigid = GetComponent<Rigidbody2D>();
spriteRenderer = GetComponent<SpriteRenderer>();
capcollider = GetComponent<CapsuleCollider2D>();
Invoke("Think", 5); // 초기화 함수 안에 넣어서 실행될 때 마다(최초 1회) nextMove변수가 초기화 되도록함
if(gameObject.name=="Slime"){
hp = 50;
op = 5;
given_exp=50;
given_money = 10;
}
else if(gameObject.name =="Mushroom"){
hp = 60;
op = 5;
given_exp=5;
given_money = 15;
}
else if(gameObject.name =="Treemon"){
hp = 75;
op=10;
given_exp=52;
given_money = 20;
}
else{
hp=100;
op=10;
given_exp=5;
given_money = 10;
}
}
// Update is called once per frame
void FixedUpdate()
{
//Move
rigid.velocity = new Vector2(nextMove,rigid.velocity.y); //nextMove 에 0:멈춤 -1:왼쪽 1:오른쪽 으로 이동
//Platform check(맵 앞이 낭떨어지면 뒤돌기 위해서 지형을 탐색)
//자신의 한 칸 앞 지형을 탐색해야하므로 position.x + nextMove(-1,1,0이므로 적절함)
Vector2 frontVec = new Vector2(rigid.position.x + nextMove*2, rigid.position.y);
//한칸 앞 부분아래 쪽으로 ray를 쏨
Debug.DrawRay(frontVec, Vector3.down*50, new Color(0,1,0));
//레이를 쏴서 맞은 오브젝트를 탐지
RaycastHit2D raycast_platform = Physics2D.Raycast(frontVec, Vector3.down,50,LayerMask.GetMask("Platform"));
//탐지된 오브젝트가 null : 그 앞에 지형이 없음
if(raycast_platform.collider == null){
nextMove= nextMove*(-1); //우리가 직접 방향을 바꾸어 주었으니 Think는 잠시 멈추어야함
CancelInvoke(); //think를 잠시 멈춘 후 재실행
Invoke("Think",5);
}
}
void Think(){//몬스터가 스스로 생각해서 판단 (-1:왼쪽이동 ,1:오른쪽 이동 ,0:멈춤 으로 3가지 행동을 판단)
//Random.Range : 최소<= 난수 <최대 /범위의 랜덤 수를 생성(최대는 제외이므로 주의해야함)
nextMove = Random.Range(-1,2);
float time = Random.Range(2f, 5f); //생각하는 시간을 랜덤으로 부여
//Think(); : 재귀함수 : 딜레이를 쓰지 않으면 CPU과부화 되므로 재귀함수쓸 때는 항상 주의 ->Think()를 직접 호출하는 대신 Invoke()사용
Invoke("Think", time); //매개변수로 받은 함수를 time초의 딜레이를 부여하여 재실행
}
public void OnDamaged(int op){
gameObject.layer = 15;
//체력감소
if(hp>0){
//깜빡거리기
StartCoroutine("Blinking");
hp -= op;
if(hp<=0)
Die();
}
else{
Die();
}
Invoke("OffDamaged",1.5f);
}
void OffDamaged(){ //무적해제함수
gameObject.layer = 10; //플레이어 레이어로 복귀함
spriteRenderer.color = new Color(1,1,1,1); //투명도를 1로 다시 되돌림
}
//깜빡거리는 함수
IEnumerator Blinking(){
Debug.Log("Monster Blink");
int countTime=0;
while(countTime<6){
if(countTime%2==0){
spriteRenderer.color = new Color(1,0,0,1);
}
else{
spriteRenderer.color = new Color(1,1,1,1);
}
yield return new WaitForSeconds(0.3f);
countTime++;
}
spriteRenderer.color = new Color(1,1,1,1);
yield return null;
}
void Die(){
//Sprite Alpha : 색상 변경
spriteRenderer.color = new Color(1,1,1,0.4f);
//Sprite Flip Y : 뒤집어지기
spriteRenderer.flipY = true;
//Collider Disable : 콜라이더 끄기
capcollider.enabled = false;
//Die Effect Jump : 아래로 추락(콜라이더 꺼서 바닥밑으로 추락함 )
rigid.AddForce(Vector2.up*5, ForceMode2D.Impulse);
//Destroy
Invoke("DeActive",5);
}
public int money_result(){
return given_money;
}
public int exp_result(){
return given_exp;
}
//비활성화
void DeActive(){ //오브젝트 끄기
gameObject.SetActive(false);
}
}
인공지능으로 움직이기 / 데미지 입기 / 몬스터 죽기 / exp. / money넘겨주기 ->근데 ㅈ금 exp바꿔둔 상태라 원ㅅ아복귀해야함
728x90