etc-posts/Unity :: C# 튜토리얼

[유니티 C#][기초] 4. 마우스, 키보드 입력 받기

플라즈밍 2018. 7. 8. 18:15
반응형



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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class PlayerControler2 : MonoBehaviour
{
    
    public float speed = 15f;//캐릭터 이동속도
    private Rigidbody rb;
    private int floorLayerMask;//마우스 레이케스트에 필요한 레이어
    private const float maxDistance = 1000f;// 레이캐스트 최대거리
 
    public void Awake()
    {
        rb = GetComponent<Rigidbody>();
        floorLayerMask = LayerMask.GetMask("Floor");
    }
 
    public void FixedUpdate()
    {
        Move();
        Turning();
    }
 
    private void Move()
    {
        var h = Input.GetAxisRaw("Horizontal");
        var v = Input.GetAxisRaw("Vertical");
 
        var direction = new Vector3(h, 0.0f, v);
        direction.Normalize();
 
        var deltaPos = direction * speed * Time.deltaTime;
        var nextPos = transform.position + deltaPos;
 
        rb.MovePosition(nextPos);
    }
 
    private void Turning()
    {
        //UnityEngine.Ray라는 클래스 사용
        //Camera.main.ScreenPointToRay(Input.mousePosition) 암기
        var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        //Physics.Raycast는 Ray 광선 + RaycastHit 결과 + 거리 + (마스크) 로 구성
        //레이 정보가 없으면 함수 종료
        if (!Physics.Raycast(ray, out hit, maxDistance, floorLayerMask))
            return;
 
        Vector3 playerToMouse = hit.point - transform.position;
        playerToMouse.y = 0f;
        //Quaternion.LookRotation -> 현재 내 로테이션에서 바라보는곳 로테이션 구함??
        Quaternion newRotatation = Quaternion.LookRotation(playerToMouse);
        //RigidBody.포지션,로테이션
        rb.MoveRotation(newRotatation);
    }
}
 
cs


반응형