본문 바로가기

Unity(C#)

Player 이동하기

Player 이동구현

 

플레이어는 왼쪽 오른쪽으로 이동이 가능하다.

Input.GetKey(KeyCode.)로 플레이어의 이동할려는 값을 받아온다.

그냥 단순하게 자기자신.x * speed * Time.deltaTime 을해주면된다. 마지막에 Time.deltaTime을 곱해주는 이유는

컴퓨터마다 성능이 다르기때문에 그걸 맞춰주기 위해서이다.

이렇게 하면 이동은끝이난다.

그 다음으로는 이동을 할때 벽을 체크를해주어야한다.

벽을 체크해주지 않을경우 벽으로 게속 이동할경우 벽으로약간들어갔다가 나왔다가하는 문제가 생기기때문에

플레이어의 이동방향으로 RayCast를 쏴서 이동이 불가능하게 만들어 주어야한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  void Move() // 이동
    {
        move = this.transform.position;
        Vector3 tempPos = this.transform.position;
        tempPos.y -= 1.5f;
 
        if (Input.GetKey(KeyCode.RightArrow)) // 오른쪽이동
        {
            if (HelpEvent.GetInstance().MoveCorrection(Vector2.right, tempPos, 0.9f))
            {
                move.x += state.warkSpeed * Time.deltaTime;
                this.transform.rotation = Quaternion.Euler(000);
            }
        }
        else if (Input.GetKey(KeyCode.LeftArrow)) // 왼쪽이동
        {
            if (HelpEvent.GetInstance().MoveCorrection(Vector2.left, tempPos, 0.9f))
            {
                move.x -= state.warkSpeed * Time.deltaTime;
                this.transform.rotation = Quaternion.Euler(0-1800);
            }
        }
        this.transform.position = move;
    }
 
 

이동을 시켜주는 함수의모습이다.

1
2
3
4
5
6
7
8
9
10
11
12
    public bool MoveCorrection(Vector2 dir, Vector3 thispos , float dis)
    {
        float maxDistance = dis;
        Vector3 pos = thispos;
        pos.y += 0.5f;
        
        if (Physics2D.Raycast(pos, dir, maxDistance, (1 << 12)))
        {
            return false;
        }
        return true;
    }
 

앞에 벽이있는지 체크해주는 함수이다.

'Unity(C#)' 카테고리의 다른 글

Unity(C#) Event  (0) 2020.04.21
Unity(C#) delegate  (0) 2020.04.21
Inspector에 변수 재목정하기  (0) 2020.03.05
Unity(C#) namespace사용방법  (0) 2019.11.06
CameraShake 만들기  (0) 2019.11.05