아카이브

주말과제(Dog Knight) 본문

유니티 기초

주말과제(Dog Knight)

timbercat 2023. 8. 6. 05:16

강아지 직선이동

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

public class DogController : MonoBehaviour
{
    public float moveSpeed = 1f;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (this.transform.position.z >= 13.0) //강아지 현재 z위치 10
        {
            //이동 멈추기
        }
        else
        {
            //이동 
            this.transform.Translate(Vector3.forward * this.moveSpeed * Time.deltaTime);
        }
    }
}

 

this.transform.Translate(방향 * 속도* 시간)

 

 

대각선 이동

첫 번째

this.transform.LookAt(target); 으로 타겟지점 바라보기

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

public class DogController : MonoBehaviour
{
    public Transform target;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        this.transform.LookAt(target);
    }
}

인스펙터 스크립트의 타겟을 임의로 정한 게임오브젝트로 설정

두 번째

타겟을 본 지점으로 직선이동

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

public class DogController : MonoBehaviour
{    
    public Transform target;    
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        //거리구하기
        //end - start : 방향 벡터
        Vector3 dir = this.target.position - this.transform.position;
        float distance = dir.magnitude; //벡터의 길이
        Debug.Log(distance);

        if (distance <= 0.1f)
        {
            //거리가 0.1보다 작으면 이동 멈추기
        }
        else
        {
            //이동
            //월드좌표계로 설정
            this.transform.Translate(transform.forward * 1f * Time.deltaTime, Space.World);
            this.transform.LookAt(target);
        }
                         
    }
}

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

아이템 착용하기  (0) 2023.08.11
클릭한 위치에 몬스터 생성/삭제  (0) 2023.08.10
유니티짱 직선으로 움직이기  (0) 2023.08.04
8/1 유니티 복습  (0) 2023.08.02
7/31 유니티 복습  (0) 2023.07.31