코드
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public bool isPressLeftArrow = false;
public bool isPressRightArrow = false;
public bool isPressUpArrow = false;
public bool isPressDownArrow = false;
public int prevKey = 0; // -1 : left, 1 : right
public float speed = 2.0f;
private Animator animator;
// Start is called before the first frame update
void Start()
{
this.animator = this.GetComponent<Animator>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
this.isPressLeftArrow = true;
if (this.isPressRightArrow)
{
prevKey = 1;
this.isPressRightArrow = false;
}
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
this.isPressRightArrow = true;
if (this.isPressLeftArrow)
{
prevKey = -1;
this.isPressLeftArrow = false;
}
}
if (Input.GetKeyDown(KeyCode.UpArrow))
{
this.isPressUpArrow = true;
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
this.isPressDownArrow = true;
}
if (Input.GetKeyUp(KeyCode.LeftArrow))
{
this.isPressLeftArrow = false;
if (this.prevKey == -1) //내가 띤 키가 이전 키라면 초기화
{
this.prevKey = 0;
}
if (this.prevKey == 1)
{
this.isPressRightArrow = true;
this.prevKey = 0;
}
}
if (Input.GetKeyUp(KeyCode.RightArrow))
{
this.isPressRightArrow = false;
if (this.prevKey == 1) //내가 띤 키가 이전 키라면 초기화
{
this.prevKey = 0;
}
if (this.prevKey == -1)
{
this.isPressLeftArrow = true;
this.prevKey = 0;
}
}
if (Input.GetKeyUp(KeyCode.UpArrow))
{
this.isPressUpArrow = false;
}
if (Input.GetKeyUp(KeyCode.DownArrow))
{
this.isPressDownArrow = false;
}
int h = 0;
if (this.isPressLeftArrow) h = -1;
else if (this.isPressRightArrow) h = 1;
else h = 0;
//Debug.LogFormat("{0}, {1}", this.isPressLeftArrow, this.isPressRightArrow);
this.animator.SetBool("IsPressLeftArrow", this.isPressLeftArrow);
this.animator.SetBool("IsPressRightArrow", this.isPressRightArrow);
//float v = Input.GetAxis("Vertical"); //키보드 입력을 -1... 0 ... 1 까지 수로 반환 (소수점)
//float h = Input.GetAxis("Horizontal");
float v = Input.GetAxisRaw("Vertical"); //키보드 입력을 -1, 0, 1 까지 수로 반환 (정수)
//float h = Input.GetAxisRaw("Horizontal");
if (Input.GetKey(KeyCode.LeftArrow) && Input.GetKey(KeyCode.RightArrow))
{
//키가 두개 좌우 눌려져있는 상태라면 위 키를 누르면 좌우를 0으로 만든다
if (v != 0)
{
h = 0;
}
}
Vector2 dir = new Vector2(h, v);
Debug.LogFormat("dir: {0}", dir);
this.transform.Translate(dir * this.speed * Time.deltaTime);
}
}
'Unity > 수업 내용' 카테고리의 다른 글
[2D]프로젝트Play&plane - 적기 생성 및 사망 (0) | 2021.10.14 |
---|---|
[2D]프로젝트Play&plane - 레이어 된 배경 스크롤링 (0) | 2021.10.14 |
[2D]프로젝트Play&plane - 미사일 생성 및 발사 (0) | 2021.10.13 |
[2D]프로젝트Play&plane -키보드 컨트롤 (애니메이션) (0) | 2021.10.13 |
유니티 프로젝트 기획하기(Play&plane) (0) | 2021.10.13 |