코드로 장애물 움직이기

양 옆으로 왔다 갔다 하는 장애물을 만들 예정이다.

[SerializeField]하고 [Range( , )]를 flaot 값 앞에 붙이면 인스펙터에 슬라이더처럼 생긴다.

[Range(,)]
슬라이더

 

Sine

Sin은 펜으로 나무디스크를 돌 때 균일한 속도로 종이가 움직이며 생긴 파형처럼 생성된다.

- 주기 : x축으로 다시 같은 지점까지 올 때까지의 크기 (걸리는 시간)

- 진폭 : y축으로 중앙부터 꼭짓점까지의 크기

SIn Cos

Tau

반지름이 1인 원에서 반지름을 길이 1의 호로 나타냈을 때의 각도가 radian이다. 여기서 3.14~~radian이 ㅠ(파이)고 6.28~~radian T(타우)다.  

타우

 

Nan 오류

어떠한 값을 0으로 나누려 할 때 뜬다.

NaN

float 값을 0과 비교해야할 일이 있을 때 Mathf.Epsilon을 사용한다.

Mathf.Epsilon

 

Oscillator.cs

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

public class Oscillator : MonoBehaviour
{
    private Vector3 startingPosition;
    
    [SerializeField] private float period = 2f;
    
    [SerializeField] private Vector3 movementVector;
    private float movementFactor;
    void Start()
    {
        startingPosition = transform.position;
        Debug.Log(startingPosition);
    }

    void Update()
    {
        //if (period <= 0) return; 
        if (period == Mathf.Epsilon) return; // float 같은 소수에 0과 비교할 때 사용 
        float cycles = Time.time / period; // 시간에 따라 계속 증가
        
        const float tau = Mathf.PI * 2; // 6.283 일정한 값
        float rawSinWave = Mathf.Sin(cycles * tau); // -1~1

        movementFactor = (rawSinWave + 1f) / 2; // 0~2 -> 0~1
        
        Vector3 offset = movementVector * movementFactor;
        transform.position = startingPosition + offset;
    }
}

 

 

플레이 영상

잘 움직이는 모습

플레이 영상

 

+ Recent posts