1. Collider와 리지드바디를 추가하여 원하는 설정값을 넣는다.
1. 만들 게임은 중력이 작용하지 않으므로 RigidBody에서 중력을 0으로 설정
2. 적당한 사이즈로 콜라이더 크기 조절
2. 입력에 따른 이동 스크립트
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] private float speed;
private Vector2 inputVec;
private Rigidbody2D rigid;
private Collider2D col;
private void Awake()
{
rigid = GetComponent<Rigidbody2D>();
col = GetComponent<Collider2D>();
}
private void Update()
{
inputVec.x = Input.GetAxisRaw("Horizontal");
inputVec.y = Input.GetAxisRaw("Vertical");
}
private void FixedUpdate()
{
Vector2 nextVec = inputVec * speed * Time.fixedDeltaTime;
rigid.MovePosition(rigid.position + nextVec);
}
}
3. 이동 방향에 따라 스프라이트 반전
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] private float speed;
private Vector2 inputVec;
private Rigidbody2D rigid;
private Collider2D col;
private SpriteRenderer spriter;
private void Awake()
{
rigid = GetComponent<Rigidbody2D>();
col = GetComponent<Collider2D>();
spriter = GetComponent<SpriteRenderer>();
}
private void Update()
{
inputVec.x = Input.GetAxisRaw("Horizontal");
inputVec.y = Input.GetAxisRaw("Vertical");
}
private void FixedUpdate()
{
Vector2 nextVec = inputVec * speed * Time.fixedDeltaTime;
rigid.MovePosition(rigid.position + nextVec);
}
private void LateUpdate()
{
if (inputVec.x != 0)
{
spriter.flipX = inputVec.x > 0;
}
}
}
4. 애니메이션 추가
사전 작업을 아래 사진과 같이 조절한다.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] private float speed;
private Vector2 inputVec;
private Rigidbody2D rigid;
private Collider2D col;
private SpriteRenderer spriter;
private Animator anim;
private void Awake()
{
rigid = GetComponent<Rigidbody2D>();
col = GetComponent<Collider2D>();
spriter = GetComponent<SpriteRenderer>();
anim = GetComponent<Animator>();
}
private void Update()
{
inputVec.x = Input.GetAxisRaw("Horizontal");
inputVec.y = Input.GetAxisRaw("Vertical");
}
private void FixedUpdate()
{
Vector2 nextVec = inputVec * speed * Time.fixedDeltaTime;
rigid.MovePosition(rigid.position + nextVec);
}
private void LateUpdate()
{
// 단순 Vector의 크기로 애니메이션에 적용하기 위해 magnitude를 사용
anim.SetFloat("Speed", inputVec.magnitude);
if (inputVec.x != 0)
{
spriter.flipX = inputVec.x > 0;
}
}
}
골드메탈 유튜브 - 유니티 뱀서라이크