Pv_log

Programming Simple Functionality: Next Steps) Lesson 6.2 - Research and Troubleshooting 본문

Unity Learn 번역/Pathway: Junior Programmer

Programming Simple Functionality: Next Steps) Lesson 6.2 - Research and Troubleshooting

Priv 2021. 7. 24. 18:16

출처

 

Lesson 6.2 - Research and Troubleshooting - Unity Learn

Overview: In this lesson, you will attempt to add a speedometer and RPM display for your vehicle in Prototype 1. In doing so, you will learn the process of doing online research when trying to implement new features and troubleshoot bugs in your projects.

learn.unity.com


 

 

1. 자동차가 힘을 사용하도록 만들기

만약 여러분이 속도계를 구현하고자 한다면, 가장 먼저 자동차가 현실의 자동차처럼 가속, 감속할 수 있도록 Translate 메서드가 아니라 힘을 사용하도록 만들어야 합니다.

 


(영상: 링크 참조)

 

Lesson 6.2 - Research and Troubleshooting - Unity Learn

Overview: In this lesson, you will attempt to add a speedometer and RPM display for your vehicle in Prototype 1. In doing so, you will learn the process of doing online research when trying to implement new features and troubleshoot bugs in your projects.

learn.unity.com


 

1. Prototype 1 프로젝트를 여시고, 파일을 백업해주세요.

2. Translate를 자동차의 리지드바디(Rigidbody)에서 AddForce 호출로 바꾸시고, "speed" 변수를 "horsePower"로 이름을 변경해주세요.

3. horsePower 값을 자동차가 움직일 수 있을 정도로 높여주세요.

4. 자동차가 적절한 방향으로 움직일 수 있도록, AddForce를 AddRelativeForce로 바꿔주세요.

 

 


 

2. 자동차가 전복되는 것 방지하기

이제 자동차에 현실적인 물리를 구현시켰으므로, 전복되기가 매우 쉬워졌습니다. 여러분의 자동차를 안전하게 운전할 수 있는 방법을 찾아야 합니다.

 


(영상: 링크 참조)

 

Lesson 6.2 - Research and Troubleshooting - Unity Learn

Overview: In this lesson, you will attempt to add a speedometer and RPM display for your vehicle in Prototype 1. In doing so, you will learn the process of doing online research when trying to implement new features and troubleshoot bugs in your projects.

learn.unity.com


 

1. 자동차의 바퀴에 휠 콜라이더(wheel collider)를 추가하시고, 크기와 중앙 위치를 수정해주세요. 그런 다음 바퀴의 다른 콜라이더들을 비활성화해주세요.

2. GameObject centerOfMass라는 새로운 변수를 생성하시고, Start()에서 playerRB 변수를 centerOfMass 위치에 할당해주세요.

3. "Center Of Mass"라는 새로운 자동차의 공백 자식 오브젝트를 생성하시고, 위치를 조정하신 뒤, 해당 오브젝트를 inspector 창에서 Center Of Mass 변수에 할당해주세요.

4. 다양한 질량 중심 위치, 속도, 회전 속도 값들을 테스트하셔서 자동차를 원하는 대로 조작할 수 있도록 만들어주세요.

더보기

*주석) 세팅 권장 값
Center Of Mass: (0, 1.25, 0.4)
Wheel Collider: Mass(20), Radius(0.39), Center(0, 0.15, 0)
RigidBody(Car): Mass(1000)

 

 


 

3. 화면에 속도계 추가하기

이제 여러분의 자동차가 반-주행 가능 상태가 되었으므로, 사용자 인터페이스(UI)에 속도를 표시해보겠습니다.

 


(영상: 링크 참조)

 

Lesson 6.2 - Research and Troubleshooting - Unity Learn

Overview: In this lesson, you will attempt to add a speedometer and RPM display for your vehicle in Prototype 1. In doing so, you will learn the process of doing online research when trying to implement new features and troubleshoot bugs in your projects.

learn.unity.com


 

1. "Speedometer Text"라는 이름의 TextMeshPro - Text 오브젝트를 새로 추가해주세요.

2. TMPro 라이브러리를 추가하시고, TextmeshProUGUI 변수를 새로 생성하여 speedometerText에 할당해주세요.

3. 속도 값을 저장할 float형 변수를 새로 만들어주세요.

4. Update()에서 mph 또는 kph 단위에 맞게 속도를 계산하신 뒤, 속도 값을 UI 상에 출력되도록 만들어주세요.

 

 


 

4. 화면에 RPM 추가하기

자동차 시뮬레이터의 또 다른 한 가지 멋진 기능은 RPM(분당 회전수) 표시입니다. 이 기능의 까다로운 부분은 어떻게 값을 계산할 것인가입니다.

 


(영상: 링크 참조)

 

Lesson 6.2 - Research and Troubleshooting - Unity Learn

Overview: In this lesson, you will attempt to add a speedometer and RPM display for your vehicle in Prototype 1. In doing so, you will learn the process of doing online research when trying to implement new features and troubleshoot bugs in your projects.

learn.unity.com


 

1. 새로운 "RPM Text" 오브젝트를 생성하시고, 해당 타입의 rpmText 변수를 새로 생성할당해주세요.

2. Update() 안에서, 계수/나머지 연산자 (%)를 사용하여 RPM을 계산하신 뒤, UI 상에 값을 출력해주세요.

 

 


 

5. 공중 주행 방지하기

이제 거의 모든 기능을 갖춘 자동차를 만들었으므로, 여러분이 고쳐야 되는 한 가지 큰 버그가 있습니다: 자동차가 공중에서도 가속/감속, 회전 및 속도/rpm 증가가 가능합니다!

 


(영상: 링크 참조)

 

Lesson 6.2 - Research and Troubleshooting - Unity Learn

Overview: In this lesson, you will attempt to add a speedometer and RPM display for your vehicle in Prototype 1. In doing so, you will learn the process of doing online research when trying to implement new features and troubleshoot bugs in your projects.

learn.unity.com


 

1. allWheels (또는 frontWheels/backWheels)라는 이름의 WheelColliders의 새로운 리스트를 선언하시고, inspector 창에서 각각의 바퀴들을 리스트에 할당해주세요.

2. int wheelsOnGround라는 새로운 변수를 선언해주세요.

3. 모든 바퀴가 땅에 닿았으면 true를, 그렇지 않으면 false를 반환하는 bool IsOnGround() 메서드를 작성해주세요.

4. 가속, 회전 속도/rpm 기능들을 자동차가 땅에 닿았는지 여부를 검사하는 if 문 안에 넣어주세요.

 

PlayerController

using System.Collections;
using System.Collections.Generic;
using System.Numerics;
using UnityEngine;
using TMPro;

public class PlayerController : MonoBehaviour
{

    [SerializeField] float speed;
    [SerializeField] float rpm;
    [SerializeField] private float horsePower = 0;
    [SerializeField] float turnSpeed = 30.0f;
    private float horizontalInput;
    private float forwardInput;
    private Rigidbody playerRb;

    [SerializeField] GameObject centerOfMass;
    [SerializeField] TextMeshProUGUI speedometerText;
    [SerializeField] TextMeshProUGUI rpmText;

    [SerializeField] List<WheelCollider> allWheels;
    [SerializeField] int wheelsOnGround;

    private void Start()
    {
        playerRb = GetComponent<Rigidbody>();
        playerRb.centerOfMass = centerOfMass.transform.position;
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        //Get Input from player
        horizontalInput = Input.GetAxis("Horizontal");
        forwardInput = Input.GetAxis("Vertical");

        if (IsOnGround())
        {

            //Move the vehicle forward
            //transform.Translate(Vector3.forward * Time.deltaTime * speed * forwardInput);
            playerRb.AddRelativeForce(Vector3.forward * forwardInput * horsePower);
            //Turning the vehicle
            transform.Rotate(Vector3.up * Time.deltaTime * turnSpeed * horizontalInput);

            //print speed
            speed = Mathf.RoundToInt(playerRb.velocity.magnitude * 2.237f);
            speedometerText.SetText("Speed: " + speed + " mph");

            //print RPM
            rpm = Mathf.Round((speed % 30) * 40);
            rpmText.SetText("RPM: " + rpm);
        }
    }

    bool IsOnGround()
    {
        wheelsOnGround = 0;
        foreach (WheelCollider wheel in allWheels)
        {
            if (wheel.isGrounded)
            {
                wheelsOnGround++;
            }
        }
        if (wheelsOnGround == 4)
        {
            return true;
        } else
        {
            return false;
        }
    }
}

 


 

6. 내용 복습

새로 배운 개념과 기술들

- 유니티 답변, 포럼, 스크립팅 API 탐색

- 버그 해결을 위한 트러블슈팅(Troubleshooting)

- AddRelativeForce, 질량 중심(Center of Mass), RoundToInt(반올림/반내림)

- 계수/나머지 연산자 (%)

- 리스트 반복

- 불리언 값을 반환하는 사용자 정의 메서드

 


 


수고하셨습니다!


Comments