Vector2를 계산해 transform.position에 대입해 좌표이동
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayController : MonoBehaviour
{
[SerializeField]
private float speed =1;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector2 position = transform.position;
if(Input.GetKey(KeyCode.A)){
position.x += -0.1f * speed * Time.deltaTime;
}
if(Input.GetKey(KeyCode.D)){
position.x += 0.1f * speed * Time.deltaTime;
}
if(Input.GetKey(KeyCode.W)){
position.y += 0.1f * speed * Time.deltaTime;
}
if(Input.GetKey(KeyCode.S)){
position.y += -0.1f * speed * Time.deltaTime;
}
transform.position = position;
}
}
[SerializeField] 를 이용해 Unity에서 속성값으로 변경할 수 있도록 지정
private float speed =1;
Rigidbody2D.velocity를 이용한 좌표이동
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayController : MonoBehaviour
{
private Rigidbody2D rd2D;
[SerializeField]
private float speed =1;
// Start is called before the first frame update
void Start()
{
rd2D = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
private void FixedUpdate()
{
float hor = Input.GetAxis("Horizontal");
rd2D.velocity = new Vector2(hor*speed,rd2D.velocity.y);
}
}
조작할 Object에 Rigidbody2D를 추가하고 다음 스크립트를 적용
Gravity Scale = 중력개념
대각선 이동 보정
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
Vector2 inputVec;
private Rigidbody2D rd2D;
[SerializeField]
private float speed =1;
void Start()
{
rd2D = GetComponent<Rigidbody2D>();
}
private void Update() {
inputVec.x = Input.GetAxisRaw("Horizontal");
inputVec.y = Input.GetAxisRaw("Vertical");
}
private void FixedUpdate()
{
Vector2 nexrtVec = inputVec.normalized * speed * Time.fixedDeltaTime;
rd2D.MovePosition(rd2D.position+inputVec);
}
}
Time.fixedDeltaTime = FixedUpdate하는 시간
normalized = 대각선의 경우 피타고라스 정의에 의해 동일한 이동이 되지 않기에 가로 1 세로 1을 갔을때 2가 아닌 1로 처리해주도록 함.
기존 Input 클래스 이후에 새로운 Input System을 Unity에서 제공해주기 때문에 기존 방식에 새로운 Input Asset을 사용해봅니다.
Window > Package Manager
Packages In Project > Unity Register 클릭
InputSystem을 Instlal 합니다.
설치 후 재시작 하겠다는 경고창이 뜹니다. 저장 후 Unity를 재시작 하는 버튼을 클릭합니다.
설치 후 Player Object에 설치된 Player Input Asset을 추가합니다.
Player Input에 Actions를 추가합니다.
Player Input Actions 설정창에서 Nomalize Vector 2를 추가하여 대각선 보정과 같은 처리를 진행하도록 설정합니다.
PlayerController Script를 열어 Update 메소드를 삭제하고 다음과 같이 코드를 작성합니다.
InputSystem에서 제공하는 OnMove 메서드를 추가하여 벡터 값을 Update합니다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
Vector2 inputVec;
private Rigidbody2D rd2D;
[SerializeField]
private float speed;
void Start()
{
rd2D = GetComponent<Rigidbody2D>();
}
void OnMove(InputValue value){
inputVec = value.Get<Vector2>();
}
void FixedUpdate()
{
Vector2 nexrtVec = speed * Time.fixedDeltaTime;
rd2D.MovePosition(rd2D.position+nexrtVec);
}
}