유니티 기초

유니티짱 마우스로 움직이기

송현호 2023. 8. 4. 18:01
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class UnityChanController : MonoBehaviour
{
    Rigidbody rBody;
    Animator anim;
    public Vector3 force;
    public float length;
    public int state = 0;
    public int moveState = 0;
    public Vector3 mouseInput;
    public RaycastHit hitData;
    // Start is called before the first frame update
    void Start()
    {
        rBody = GetComponent<Rigidbody>();
        anim = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            Debug.DrawRay(ray.origin, ray.direction * 1000f, Color.red, 1f);
            RaycastHit hitData;
            //Ray와 충동되면 
            if (Physics.Raycast(ray.origin, ray.direction * 1000f, out hitData))
            {
                //충동된 정보가 hitData에 담긴다 
                // hitData.point : 충돌된 지점의 좌표 (월드)
                this.transform.LookAt(hitData.point);
                this.hitData = hitData;
                moveState = 1;
            }
        }
        Move();
        Debug.Log((this.transform.position - hitData.point).magnitude);
        //Attack();

    }

    public void Move()
    {

        if ((this.transform.position - hitData.point).magnitude > 0.05f && moveState == 1)
        {
            state = 1;

            Vector3 move = hitData.point * Time.deltaTime;
            this.length += move.magnitude;
            this.rBody.transform.Translate(Vector3.forward/20f);
            this.anim.SetInteger("state", state);
        }

        else
        {
            state = 0;
            length = 0;
            moveState = 0;
            this.anim.SetInteger("state", state);
        }

        
    }
    public void MoveStart()
    {
        moveState = 1;
    }

    public void OnCollisionEnter(Collision collision)
    {
        
    }

    //public void Attack()
    //{
    //    if (Input.GetKeyDown(KeyCode.Space))
    //    {
    //        this.anim.Setbool
    //    }
    //}
}

RayCast를 이용해 충돌지점의 정보를 저장한다음 캐릭터의 위치가 충돌지점의 위치의 차이가 0.05이상일때 움직이도록 코드를 짰다.

 

'유니티 기초' 카테고리의 다른 글

바구니 게임  (0) 2023.08.07
유닛 이동하여 공격하기  (0) 2023.08.04
밤송이 던지기  (0) 2023.08.04
유니티 애니메이션(점프)  (0) 2023.08.03
유니티 애니메이션  (0) 2023.08.03