" /> 과제 1 - 특정 위치로 이동하는 오브젝트 | BlackWerf's Blog
포스트

과제 1 - 특정 위치로 이동하는 오브젝트

목차

과제 내용

  • 하나의 오브젝트가 6개의 점을 돌고 시작점으로 이동하는 스크립트 구현하기

프로젝트 링크

작업한 프로젝트는 다음의 링크에서 확인할 수 있습니다

코드 링크


프로젝트 모습


사용한 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
    using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    public GameObject A, B, C, D, E, F, Object, Origin;

    Vector3 target;
    // Start is called before the first frame update
    void Start()
    {
        target = A.transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 v = target - Object.transform.position;
        Vector3 cross = Vector3.Cross(Object.transform.forward, v.normalized);
        Quaternion q = Quaternion.AngleAxis(0.5f, cross);

        Object.transform.rotation = q * Object.transform.rotation;

        Object.transform.position = Object.transform.position +
                Object.transform.forward * 4f * Time.deltaTime;

        if (Vector3.Distance(Object.transform.position, A.transform.position) <= 0.5f)
            target = B.transform.position;

        else if (Vector3.Distance(Object.transform.position, B.transform.position) <= 0.5f)
            target = C.transform.position;

        else if (Vector3.Distance(Object.transform.position, C.transform.position) <= 0.5f)
            target = D.transform.position;

        else if (Vector3.Distance(Object.transform.position, D.transform.position) <= 0.5f)
            target = E.transform.position;

        else if (Vector3.Distance(Object.transform.position, E.transform.position) <= 0.5f)
            target = F.transform.position;

        else if (Vector3.Distance(Object.transform.position, F.transform.position) <= 0.5f)
            target = Origin.transform.position;
    }
}


코드 설명

  • 변수:

  • GameObject

    A, B, C, D, E, F, Object, Origin

    ABCDEF: Object 오브젝트가 이동할 위치의 오브젝트입니다

    Object: 움직일 오브젝트

    Origin: F까지 이동 이후 첫 위치로 이동할 좌표의 오브젝트

  • Vector3

    target: 이동할 위치 값을 가집니다


  • Vector3.Cross: 두 개의 벡터의 교차 곱을 반환하는 함수
    • 두 개의 입력된 값의 크기를 곱한 후, 입력된 값의 각도의 Sin값을 곱한 값을 반환함
    • y값이 -면 왼쪽으로, +면 오른쪽으로 이동함


이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.