캐릭터 이동 구현 시 Animator Controller의 Parameters는 float 혹은 int형 파라미터를 추가하여 키 입력을 판단합니다.
State Machine 에서 Idle 상태를 중심으로 상하좌우로 가는 Transition을 설정합니다.
Has Exit Time은 현재 애니메이션을 끝까지 보고 다음으로 넘어갈지 바로 넘어갈지를 결정하는 도구입니다.
캐릭터 이동 코드 예시
void Update()
{
// A키: 왼쪽 이동
if (Input.GetKey(KeyCode.A)) {
animator.SetBool("isLeft", true);
}
else {
animator.SetBool("isLeft", false);
}
// S키: 뒤로 이동
if (Input.GetKey(KeyCode.S)) {
animator.SetBool("isRunBack", true);
}
else {
animator.SetBool("isRunBack", false);
}
// D키: 오른쪽 이동
if (Input.GetKey(KeyCode.D)) {
animator.SetBool("isRight", true);
}
else {
animator.SetBool("isRight", false);
}
}
using UnityEngine;
public class PushableBlock : MonoBehaviour
{
//
public float pushSensitivity = 5.0f;
private Rigidbody rb; // rigidbody 가져오기
void Start()
{
rb = GetComponent<Rigidbody>();
}
// 무언가와 계속 닿아있을 때
void OnCollisionStay(Collision collision)
{
// 닿은 물체가 Player 일때만 작동
if (collision.gameObject.CompareTag("Player"))
{
// 플레이어 위치 - 블럭 위치 = 나를 바라보는 방향 벡터 (왼쪽에서 밀면 +x)
Vector3 direction = transform.position - collision.transform.position;
// 힘을 가해서 밀기
rb.AddForce(direction * pushSensitivity, ForceMode.Force);
}
}
}
using UnityEngine;
public class MoveBridge : MonoBehaviour
{
public float speed = 3.0f; // 이동 속도
public float moveRange = 5.0f; // 이동 범위
private Vector3 startPos;
private float _timer = 0f; // 작동 시간 누적용
private bool _isActive = false;
void Start()
{
startPos = transform.position;
}
void Update()
{
if (_isActive)
{
_timer += Time.deltaTime;
// 왕복 이동 값 계산
float zPos = Mathf.PingPong(_timer * speed, moveRange);
transform.position = startPos + new Vector3(0, 0, zPos);
}
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
_isActive = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
_isActive = false;
}
}
}
using UnityEngine;
public class VerticalDoor : MonoBehaviour
{
public float speed = 2.0f; // 문이 움직이는 속도
public float openHeight = 3.0f; // 문이 열리는 높이
private Vector3 startPos;
private float _timer = 0f;
private bool _isPlayerNear = false; // 플레이어 감지 상태
void Start()
{
startPos = transform.position;
}
void Update()
{
if (_isPlayerNear)
{
// 플레이어가 근처에 있음
_timer += Time.deltaTime;
float newY = Mathf.PingPong(_timer * speed, openHeight);
transform.position = startPos + new Vector3(0, newY, 0);
}
else
{
// 플레이어가 멀어지면 문이 원래 위치로 델타타임속도로 닫힘
// MoveTowards(현재위치, 목표위치, 속도)
transform.position = Vector3.MoveTowards(transform.position, startPos, speed * Time.deltaTime);
// 문이 완전히 닫혔다면, 다음 작동을 위해 타이머를 초기화
if (transform.position == startPos)
{
_timer = 0f;
}
}
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
_isPlayerNear = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
_isPlayerNear = false;
}
}
}