0429 조이스틱으로 캐릭터 움직이기

2021. 4. 29. 15:40unity

조이스틱은 유니티 에셋에서 가져왔음 'JoyStick Pack'

<조이스틱이 가리키는 방향으로 이동하기>

using UnityEngine;

public class JoyStickTest : MonoBehaviour
{
	//VariableJoystick은 에셋에 포함된 스크립트임
    public VariableJoystick variableJoystick;

    public Transform hero;
    public float moveSpeed=1f;
    
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        Debug.LogFormat("{0}", variableJoystick.Direction);
        var dir = new Vector3(variableJoystick.Direction.x, 0, variableJoystick.Direction.y);
        var move = dir * this.moveSpeed * Time.deltaTime;
        this.hero.Translate(move);
    }
}

 

 

종종 특정 오브젝트가 타 오브젝트를 바라보도록 해야할 때가 있다.
그럴 때 삼각함수 tan(r) = y/x로 radian 값을 불러온다.
float rad = Mathf.Atan2(float y, float x);

위의 수식은 라디안 값을 돌려주기에 degree로 변환해서 사용해야 하는데, 
기본적으로 유니티에서 회전을 표현할 땐 Quaternion을 이용한다.
각 오브젝트의 rotation 프로퍼티를 Euler angle을 이용해 사원수의 값을 반환한다.

transform.rotation = Quaternion.Euler( 90, 0, 0 );

<조이스틱이 가리키는 방향으로 캐릭터가 회전하기>

using UnityEngine;
using UnityEngine.UI;

public class JoyStickTest : MonoBehaviour
{
    public VariableJoystick variableJoystick;

    public Transform heroTrans;
    public float moveSpeed=1f;
    public Animation anim;
    public Button btnAttack;
    
    // Start is called before the first frame update
    void Start()
    {
        this.btnAttack.onClick.AddListener(() =>
        {
            this.anim.Play("attack_01");
        });
    }

    // Update is called once per frame
    void Update()
    {
        var dir = new Vector3(variableJoystick.Direction.x, 0, variableJoystick.Direction.y);
        
        //angle = 1 radian * 180 / PI
        var angle = Mathf.Atan2(dir.x, dir.z) * 180 / Mathf.PI;
        this.heroTrans.rotation = Quaternion.Euler(new Vector3(0, angle, 0));
    }
}

 

<조이스틱이 가리키는 방향으로 회전 후 이동하기>

using UnityEngine;
using UnityEngine.UI;

public class JoyStickTest : MonoBehaviour
{
    public VariableJoystick variableJoystick;

    public Transform heroTrans;
    public float moveSpeed=1f;
    public Animation anim;
    public Button btnAttack;
    
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        var dir = new Vector3(variableJoystick.Direction.x, 0, variableJoystick.Direction.y);
        if (dir == Vector3.zero) {
            return;
        }

        //angle = 1 radian * 180 / PI
        var angle = Mathf.Atan2(dir.x, dir.z) * 180 / Mathf.PI;

        this.heroTrans.rotation = Quaternion.Euler(new Vector3(0, angle, 0));

        this.heroTrans.Translate(Vector3.forward * this.moveSpeed * Time.deltaTime);
    }
}