[뇌파 VR게임] #7 초능력1 하늘 날기 구현 2

in #kr6 years ago

뇌파와 VR을 이용한 초능력 체험 게임 시리즈 글입니다.


[게임화면]

이전글 - [뇌파 VR게임] #6 초능력1 하늘 날기 구현 1


이전글에서 설정한 Waypoints을 순차적으로 따라서 이동하는 모션을 만들어 보겠습니다. 구현하고자 하는 것은 Player를 Waypoint 방향쪽으로 이동하다가 point와 충돌하면, 다음 point를 향하도록 바꿔 주는 것입니다. 여기서 충돌은 충돌이 되는지만 확인하는 것이고, 어떤 물리적 현상이 벌어지지 않습니다. 이것은 이전글에서 Waypoint의 Sphere Collider 컴포넌트의 Is Trigger 옵션을 체크해기 때문에 가능합니다.

image.png

Move 스크립트

그럼 Player가 Waypoints를 이동하도록 하는 스크립트를 구현해 보겠습니다.
아래 그림과 같이 Scripts 폴더 밑에 "MoveWaypoints"라는 스크립트를 만듭니다.
image.png

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveWaypoints : MonoBehaviour
{
    // move complete flag
    private bool move_done = false;
    // moving speed
    public float speed = 0.5f;
    // factor for rotation speed
    public float damping = 3.0f;

    private Transform tr;
    private Transform[] points;
    private int next_idx = 1;

    private Transform camTr;
    private CharacterController cc;

    // Use this for initialization
    void Start()
    {
        // get the current transform of the player
        tr = GetComponent<Transform>();
        // get the transform component of the main camera 
        camTr = Camera.main.GetComponent<Transform>();
        // get the character controller component of the Player
        cc = GetComponent<CharacterController>();

        // extract all the waypoints
        points = GameObject.Find("Waypoints").GetComponentsInChildren<Transform>();
    }

    // Update is called once per frame
    void Update()
    {
        // stop move if the move is doen
        if( !move_done )
            MoveToWaypoint();
    }

    // move to waypoint
    public void MoveToWaypoint()
    {
        // compute the vector to the next wypoint
        Vector3 direction = points[next_idx].position - tr.position;
        // compute the rotation as quaternion
        Quaternion rot = Quaternion.LookRotation(direction);
        // rotate smoothly
        tr.rotation = Quaternion.Slerp(tr.rotation, rot, Time.deltaTime * damping);
        // translate
        tr.Translate(Vector3.forward * Time.deltaTime * speed);
    }

    // event for waypoint collision
    private void OnTriggerEnter(Collider other)
    {
        // check if the Tag is the WAY_POINT
        if (other.CompareTag("WAY_POINT"))
        {
            // increase the waypoint index
            if (next_idx < points.Length - 1)
            {
                next_idx++;
                Debug.Log("waypoint: " + next_idx.ToString());
            }
            else
            {
                move_done = true;
                Debug.Log("move done");
            }
        }
    }

    // return the move doen flag
    public bool IsMoveDone()
    {
        return move_done;
    }
}

스크립트를 Player의 컴포넌트로 추가시킵니다. 스크립트 파일을 드래그하여 Hierarchy창의 Player에 드랍합니다. 그런 후에 Speed값을 3정도로 해줍니다.
image.png

한가지 주의할 것은 스크립트에 아무리 Speed의 값을 바꿔도 적용되지 않습니다. 왜냐하면 변수가 public으로 선언되었기 때문에 Inspector 컴포넌트에 적힌 값이 우선입니다. 꼭 값 변경은 Inspector에서 하세요.

이제 Unity를 실행시켜 봅니다. Scence창을 보면 카메라가 이동하는게 보이고, Game창은 카메라의 이동에 따른 화면이 나타납니다. 가끔 Point4에 도달하지 못하고, 카메라가 주변을 계속에서 도는 현상이 발생합니다.
image.png

이것은 MoveToWaypoint함수에서 Slerp이라는 함수를 사용하는데, waypoints간의 interpolation 포인트들을 계산하는데 제대로 해를 못찾아서 발생합니다. 책을 찾아보면 damping값이 작아서라고 합니다. Waypoints가 근접해 있거나, 한 waypoint에서 다음 waypoint까지의 이동이 매끄럽지 못하면 이와 같은 현상이 발생하기도 합니다. 따라서 point4의 위치를 약간 변경시켰습니다.


Waypoints를 이용해서 하늘을 나는 효과를 만들어 봤습니다. 뇌파는 아직 사용하고 있지 않고 있습니다. 모든 초능력이 구현되면 그 때 뇌파를 적용하는 부분을 구현해 보겠습니다. 안그러면 뇌파를 일일이 읽고 결과를 기다려서 테스트 해야 하는 번거로움이 발생합니다.

오늘의 실습: 방금 만든 앱을 VR로 경험해 보세요. 하늘을 나는 기분은 어떤가요?

Coin Marketplace

STEEM 0.18
TRX 0.15
JST 0.029
BTC 62938.05
ETH 2552.06
USDT 1.00
SBD 2.63