모바일용 버튼 제작

Intro

  • 모바일용 버튼 제작

버튼 세팅

1

블로그에서 다운받은 스프라이트를 임포트하고 잘라서 사용하기 위해

Sprite 모드를 Multiple로 만들고 Sprite Editor에서 Slice 해주었다

2

화면에 버튼을 추가하기위해 씬에 UI - Canvas를 넣고 그아래에 Button을 넣어줌

3

버튼에 준비한 스프라이트를 넣어준다음

4

방향키와 점프키를 화면에 적절한 위치에 배치

5

추가로 배경이 될 스프라이트를 배치

스크립트 수정

10

Player 스크립트에서 필요한 bool 변수를 선언해준다음

6

7

UIButtonManager라는 스크립트를 만들고 Manager 오브젝트에 넣어주었고

방향키는 누르고 있을때만 True , 점프키는 누를때만 True를 반환하도록 함

8

Player 스크립트에서 기존 키입력대신 InputLeft, Right 값을 통해 움직이도록 함

9

FixedUpdate에는 Move();를 추가하고

Update에는 마찬가지로 점프키 대신 inputJump값을 사용하게 수정

12

첫 게임에서는 스타트 전까지 플레이어가 없기때문에

Player 스크립트에서 따로 초기화 함수를 호출하도록 함

이벤트 트리거 추가

11

만들어 둔 Button에 Event Trigger 컴포넌트를 추가하고

Add New Event Type으로 방향키에는 Pointer Down , Pointer Up을 만든다음

Manager 오브젝트를 넣은뒤 각각 맞는 스크립트를 넣어주었다

오른쪽 방향키도 마찬가지로 해준다음

점프버튼은 PointerDown만 해주었다

문제점 해결

문제점 1

fd

점프버튼을 3번누르면 2단 점프를 한다음 착지한다음 다시 점프하게되는 문제 발생

16

UI스크립트에서 JumpClick에 if문 추가를 통해 해결

문제점 2

14

모바일 해상도에서 UI가 작게나오는 문제

버튼을 전체화면에 맞춰 키우는 방법으로 해결

소스 코드

UI

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIButtonManager : MonoBehaviour
{
GameObject player;
Player playerScript;
public void Init()
{
player = GameObject.FindGameObjectWithTag("Player");
playerScript = player.GetComponent<Player>();
}
public void LeftDown()
{
playerScript.inputLeft = true;
}
public void Leftup()
{
playerScript.inputLeft = false;
}
public void RightDown()
{
playerScript.inputRight = true;
}
public void RightUp()
{
playerScript.inputRight = false;
}
public void JumpClick()
{
if(playerScript.extraJumps !=0)
playerScript.inputJump = true;
}
}
view raw UI.cs hosted with ❤ by GitHub

Player

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public int maxHealth = 1;
bool isDie = false;
int health = 1;
public float speed;
public float jumpForce;
private float moveInput;
private Rigidbody2D rb;
private bool facingRight = true;
private bool isGrounded;
public Transform groundCheck;
public float checkRadius;
public LayerMask whatIsGround;
public int extraJumps;
public int extraJumpsValue;
public bool inputLeft = false;
public bool inputRight = false;
public bool inputJump = false;
// Use this for initialization
void Start()
{
extraJumps = extraJumpsValue;
rb = GetComponent<Rigidbody2D>();
health = maxHealth;
UIButtonManager ui = GameObject.FindGameObjectWithTag("Managers").GetComponent<UIButtonManager>();
ui.Init();
}
void FixedUpdate()
{
Move();
if (health == 0)
return;
isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
}
void Update()
{
if (health==0)
{
if (!isDie)
Die();
return;
}
if (isGrounded == true)
{
extraJumps = extraJumpsValue;
}
if (inputJump && extraJumps > 0)
{
rb.velocity = Vector2.up * jumpForce;
extraJumps--;
inputJump = false;
}
else if (inputJump && extraJumps == 0 && isGrounded == true)
{
rb.velocity = Vector2.up * jumpForce;
inputJump = false;
}
}
void Flip()
{
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
void Move()
{
Vector3 moveVelocity = Vector3.zero;
if (inputLeft)
{
moveVelocity = Vector3.left;
transform.localScale = new Vector3(-1, 1, 1);
}
else if (inputRight)
{
moveVelocity = Vector3.right;
transform.localScale = new Vector3(1, 1, 1);
}
transform.position += moveVelocity * speed * Time.deltaTime;
}
void OnTriggerEnter2D(Collider2D other)
{
//일정속도로 몬스터를 밟게되면
if (other.gameObject.tag == "Creature"&& !other.isTrigger&&rb.velocity.y<-10f)
{
Monster creature = other.gameObject.GetComponent<Monster>();
//몬스터의 Die함수 호출
creature.Die();
//바운스
Vector2 killVelocity = new Vector2(0, 30f);
rb.AddForce(killVelocity, ForceMode2D.Impulse);
//스코어 매니저에 몬스터의 점수 저장
ScoreManager.setScore(creature.score);
}
else if (other.gameObject.tag == "Creature" && !other.isTrigger && !(rb.velocity.y < -10f))
{
health=0;
}
if(other.gameObject.tag=="Bottom")
{
health = 0;
}
if (other.gameObject.tag == "Coin")
{
GetCoin coin = other.gameObject.GetComponent<GetCoin>();
ScoreManager.setScore((int)coin.value);
Destroy(other.gameObject, 0f);
}
if (other.gameObject.tag == "End")
{
other.enabled = false;
GameManager.EndGame();
}
}
void Die()
{
isDie = true;
rb.velocity = Vector2.zero;
BoxCollider2D[] colls = gameObject.GetComponents<BoxCollider2D>();
colls[0].enabled = false;
colls[1].enabled = false;
Vector2 dieVelocity = new Vector2(0, 20f);
rb.AddForce(dieVelocity, ForceMode2D.Impulse);
Invoke("RestartStage", 2f);
}
void RestartStage()
{
GameManager.RestartStage();
}
}
view raw player.cs hosted with ❤ by GitHub

실행 화면

13

참고자료

관련블로그

태그:

카테고리:

업데이트:

댓글남기기