본문 바로가기
KDT/유니티 심화

23/08/22 HeroShooter 이동하기

by 잰쟁 2023. 8. 22.
728x90

Main

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

public class GameMain1 : MonoBehaviour
{
    [SerializeField]
    private PlayerController playerController;
    [SerializeField]
    private Joystick joystick;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        //조이스틱 방향 가져오기
        float h = this.joystick.Horizontal;
        float v = this.joystick.Vertical;
        var dir = new Vector3(h, 0, v);

        //화면 밖 나가지 않게
        //float ClampX = Mathf.Clamp(this.transform.position.x, -2.7f, 2.7f);
        //float ClampY = Mathf.Clamp(this.transform.position.y, -4.6f, 4.8f);
        //this.playerTrans.position = new Vector3(ClampX,0,ClampY);

        //Player 이동시키기
        if (dir != Vector3.zero)
        {
            this.playerController.Move(dir);
        }
        else
        {
            this.playerController.Idle();
        }
    }
}

Player

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

public class PlayerController : MonoBehaviour
{
    private Transform playerTrans;
    public float moveSpeed = 5f;
    private Animator anim;
    public float turnSpeed = 80f;
   
    void Start()
    {
       this.playerTrans = this.GetComponent<Transform>();
       this.anim = this.GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    //이동 메서드
    public void Move(Vector3 dir)
    {     
        //애니메이션
        this.anim.SetInteger("State", 1);
        //회전하기
        float angle = Mathf.Atan2(dir.x, dir.z) * Mathf.Rad2Deg;
        this.playerTrans.localRotation = Quaternion.AngleAxis(angle, Vector3.up);
        //이동하기
        this.playerTrans.Translate(Vector3.forward * this.moveSpeed * Time.deltaTime);      
    }

    //정지 메서드
    public void Idle()
    {
        this.anim.SetInteger("State", 0);
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.white;
        GizmosExtensions.DrawWireArc(this.transform.position, this.transform.forward, 360, 1);
    }
}