728x90
<제3강 이동불가 지역 설정>
box collider 2D를 component 추가해준다
그 다음 edit collider로 크기를 조절한다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovingObject : MonoBehaviour{
private BoxCollider2D boxCollider;
public LayerMask layerMask; //통과가 불가능한 레이어 설정
public float speed;
private Vector3 vector;
public float runSpeed;
private float applyRunSpeed;
private bool applyRunFlag = false;
public int walkCount;
private int currentWalkCount;
private bool canMove = true;
private Animator animator;
//speed=2.4, walkCount=20
//2.4*20=48
void Start()
{
boxCollider = GetComponent<BoxCollider2D>();
animator = GetComponent<Animator>();
}
IEnumerator MoveCoroutine()
{
while (Input.GetAxisRaw("Horizontal") != 0 || Input.GetAxisRaw("Vertical") != 0)//한발씩 움직이게 함
{
if (Input.GetKey(KeyCode.LeftShift))
{
applyRunSpeed = runSpeed;
applyRunFlag = true;
}
else
{
applyRunSpeed = 0;
applyRunFlag = false;
}
vector.Set(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"), transform.position.z);
if (vector.x != 0)
{
vector.y = 0;
}//vector.x=1 우측이동
//vector.y=0
animator.SetFloat("DirX", vector.x);
animator.SetFloat("DirY", vector.y);
RaycastHit2D hit;
//A지점,B지점에 레이저가 도달하면 hit=Null;
//도달하지 못하면 hit= 방해물 리턴
Vector2 start=transform.position;//A지점, 캐릭터의 현재 위치값
Vector2 end=start+ new Vector2(vector.x*speed*walkCount, vector.y * speed * walkCount);//B지점 , 캐릭터가 이동하고자하는 위치값
boxCollider.enabled = false;
hit = Physics2D.Linecast(start, end, layerMask);//레이저를 쐈을때 b지점까지 무사히 도달하는지
boxCollider.enabled = true;
if (hit.transform != null)
{
break;
}//hit에 반환 값이 있을 경우 이후 명령어 실행시키지 않음
animator.SetBool("Walking", true);
while (currentWalkCount < walkCount)
{
if (vector.x != 0)
{
transform.Translate(vector.x * (speed + applyRunSpeed), 0, 0);
}
else if (vector.y != 0)
{
transform.Translate(0, vector.y * (speed + applyRunSpeed), 0);
}
if (applyRunFlag)
{
currentWalkCount++;
}
currentWalkCount++;
yield return new WaitForSeconds(0.01f);
}//실제 이동
currentWalkCount = 0;
}
animator.SetBool("Walking", false);
canMove = true;
}
void Update()
{
if (canMove)
{
if (Input.GetAxisRaw("Horizontal") != 0 || Input.GetAxisRaw("Vertical") != 0)
{
canMove = false;
StartCoroutine(MoveCoroutine());
}
}
}
}
layer에 Nopassing을 추가해준다
그 다음 Moving object에서 Layer Mask를 NoPassing으로 지정해준다.
다른 새로운 빈 오브젝트를 생성한다음 똑같이 Box Collider2D를 추가한다음에 레이어로 NoPassing을 지정해준다
캐릭터의 기준점을 내려줘야하는데 기준을 건드려야 하는 이유는 그 기준에서 레이저가 발사되기 때문이다.
현재 BoxCollider를 발쪽에 설정했기때문에 기준을 발쪽으로 옮겨야한다 (만약 범위를 캐릭터 전체로 설정했다면 이 과정이 필요하지 않다)
sprite editor로 들어가서 pivot를 custom으로 설정한다음 밑으로 내려준다
그 다음 scene상단에서 center를 pivoit으로 바꿔준다
728x90
'🎮 취미 > Unity' 카테고리의 다른 글
유니티 스터디 - 게임 개발 속성 강의 (2) (2) | 2024.11.15 |
---|---|
유니티 스터디 - 게임 개발 속성 강의 (1) (1) | 2024.11.08 |
유니티 쯔꾸르 게임 만들기 4 (인프런) (0) | 2023.07.01 |
유니티 쯔꾸르 게임 만들기 2 (인프런) (0) | 2023.07.01 |
유니티 쯔꾸르 게임 만들기 1 (인프런) (1) | 2023.06.30 |