Unity-14: 방향키를 이용한 이동/회전
앞, 뒤, 좌, 우 이동
public float _moveSpeed = 10;
public float _rotSpeed= 150;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float mz = Input.GetAxisRaw("Vertical"); // -1 ~ 1
float mx = Input.GetAxisRaw("Horizontal"); // -1 ~ 1
transform.position += Vector3.right * mx * _moveSpeed * Time.deltaTime;
transform.position += Vector3.forward * mz * _moveSpeed * Time.deltaTime;
}
GetAxis
보단GetAxisRaw
를 사용!!- 방향을 바꿔버리면 물체의 앞방향으로 가는게 안됨
물체가 바라보고 있는 방향으로 이동
public float _moveSpeed = 10;
public float _rotSpeed= 150;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float mz = Input.GetAxisRaw("Vertical"); // -1 ~ 1
float mx = Input.GetAxisRaw("Horizontal"); // -1 ~ 1
Vector3 dir = (transform.right * mx) + (transform.forward * mz);
dir = (dir.magnitude > 1) ? dir.normalized : dir;
transform.position += dir * _moveSpeed * Time.deltaTime;
}
```c#
{
public float _moveSpeed = 10;
public float _rotSpeed= 150;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float mz = Input.GetAxisRaw("Vertical"); // -1 ~ 1
float mx = Input.GetAxisRaw("Horizontal"); // -1 ~ 1
Vector3 dir = new Vector3(mx, 0, mz);
dir = (dir.magnitude > 1) ? dir.normalized : dir;
transform.Translate(dir * _moveSpeed * Time.deltaTime);
}
- 로컬을 기준으로 mx, mz를 만들면 알아서 내 방향으로 기준해서 계산을 해줌
옆으로 회전도 가능하도록
public float _moveSpeed = 10;
public float _rotSpeed= 150;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float mz = Input.GetAxisRaw("Vertical");
float rx = Input.GetAxisRaw("Horizontal");
float mx = Input.GetAxisRaw("Horiz");
Vector3 dir = new Vector3(mx, 0, mz);
dir = (dir.magnitude > 1) ? dir.normalized : dir;
transform.Rotate(Vector3.up*rx*Time.deltaTime*_rotSpeed);
transform.Translate(dir*Time.deltaTime*_moveSpeed);
// transform.Rotate(Vector3.up * rx * Time.deltaTime * _rotSpeed); //게걸음없이
//transform.Translate(Vector3.forward * mz * Time.deltaTime * _moveSpeed);//게걸음없이
}
카메라가 따라 다니게 하기
{
public Transform targetTransform;
public Vector3 CameraOffset;
void Update()
{
transform.position = targetTransform.position + CameraOffset;
}
- main camera에다가 넣기
댓글남기기