유니티/닷지(3D 탄막 슈팅 게임)

닷지(2) - 플레이어 스크립트 생성&입력감지

무직백수취업준비생 2021. 6. 23. 23:49
728x90
반응형

PlayerController이름으로 스크립트를 생성합니다.

 

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

public class PlayerController : MonoBehaviour
{
    public Rigidbody playerRigidbody; //이동에 사용할 리지드바디 컴포넌트
    public float speed = 8f; //이동 속력

    void Start()
    {
        
    }
    void Update()
    {
        if (Input.GetKey(KeyCode.UpArrow) == true)
        {
            //위쪽 방향키 입력이 감지된 경우 z방향 힘 주기
            playerRigidbody.AddForce(0f, 0f, speed);
        }
        if (Input.GetKey(KeyCode.DownArrow) == true)
        {
            //아래쪽 방향키 입력이 감지된 경우 -z방향 힘 주기
            playerRigidbody.AddForce(0f, 0f, -speed);
        }
        if(Input.GetKey(KeyCode.RightArrow)==true)
        {
            //오른쪽 방향키 입력이 감지된 경우 x방향 힘 주기
            playerRigidbody.AddForce(speed, 0f, 0f);
        }
        if(Input.GetKey(KeyCode.LeftArrow)==true)
        {
            //왼쪽 방향키 입력이 감지된 경우 -x방향 힘 주기
            playerRigidbody.AddForce(-speed, 0f, 0f);
        }    
    }
    public void Die()
    {
        //자신의 게임 오브젝트를 비활성화
        gameObject.SetActive(false);
    }
}

 

스크립트 작성이 끝났으면 PlayerController 스크립트를 Player 게임 오브젝트에 컴포턴트로 추가합니다.

 

 

Player Rigidbody필드에 RigidBody 컴포넌트를 할당시킵니다.

 

플레이해보면 방향키로 Player오브젝트가 움직이는걸 확인할 수 있습니다.

 

그러나 동작이 굼뜨고 무겁게 느껴집니다.

 

스크립트를 수정하겠습니다.

 

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

public class PlayerController : MonoBehaviour
{
    private Rigidbody playerRigidbody; //이동에 사용할 리지드바디 컴포넌트
    public float speed = 8f; //이동 속력

    void Start()
    {
        //게임 오브젝트에서 Rigidbody 컴포넌트를 찾아 playerRigidbody에 할당
        playerRigidbody = GetComponent<Rigidbody>();
        
    }
    void Update()
    {
        //수평축과 수직축의 입력값을 감지하여 저장
        float xInput = Input.GetAxis("Horizontal");
        float zInput = Input.GetAxis("Vertical");

        //실제 이동 속도를 입력값과 이동 속력을 사용해 결정
        float xSpeed = xInput * speed;
        float zSpeed = zInput * speed;

        //Vector3 속도를 (xSpeed, 0, zSpeed)로 생성
        Vector3 newVelocity = new Vector3(xSpeed, 0f, zSpeed);
        //리지드바디의 속도에 newVelocity 할당
        playerRigidbody.velocity = newVelocity;
    }
    public void Die()
    {
        //자신의 게임 오브젝트를 비활성화
        gameObject.SetActive(false);
    }
}

수정된 스크립트를 저장하고 유니티를 실행해보면 관성을 무시하고 즉시 플레이어의 이동 방향을 전환할 수 있습니다.

 

지난 플레이에 비해 조작이 더 빠르게 반영된다고 느껴질 겁니다.

 

 

728x90
반응형