static함수?

외부에서 접근 가능한 함수로 만들 때 사용함. 
using UnityEngine class처럼 다른 스크립트에서 접근해서 사용 가능함. 


Delegate ? 

함수에 대한 참조. 델리게이트를 사용하면 함수를 변수처럼 사용할 수 있다. 
delegate를 사용하기 위해서는 delegate라고 선언하고 return값의 자료형과 파라미터를 입력해주어야 한다. 그 후에 함수를 변수처럼 가져와 사용가능함. 배열에 담아서 사용할 수도 있다. 


Enum?

열거형. list로 키워드를 선택할 수 있도록 함. 


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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Graph : MonoBehaviour
{
    public Transform pointPrefab;
    [Range(10100)] 
    public int resolution = 10//prefab의 개수
    [Range(0.1f, 5)]
    public float height = .5f;
    [Range(150)]
    public float length = 2f;
    [Range(0100)]
    public float rotationSpeed = 50f;
    [Range(.1f, 2f)]
    public float prefabScale = 1f;
    public GraphName function; //열거형(enum) 형태 
    private Transform[] points;
 
    private void Awake()
    {
        points = new Transform[resolution]; 
        for(int i=0; i < points.Length; i++)
        {
            Transform point = Instantiate(pointPrefab);
            point.SetParent(transform, false); 
            points[i] = point; 
        }
    }
 
    private void Update()
    {
        float step = length / resolution;
        Vector3 scale = Vector3.one * prefabScale;
        float t = Time.time;
        //delegate를 통한 함수의 배열 가져오기  
        GraphFuction[] functions = { 
            SineFunction, MultiSineFunction
        };
        //delegate 함수 중 하나 선택 
        GraphFuction f = functions[(int)function];
        for (int i=0; i<points.Length; i++)
        {
            //point wave animation
            Transform point = points[i];
            Vector3 position = point.localPosition; 
            position.x = (i + 0.5f) * step - (length / 2);
            position.y = f(position.x, t); 
            position.z = 0;
            point.localPosition = position; 
            point.localScale = scale;
        }
        //x축으로 회전 
        Quaternion rotation = transform.localRotation;
        rotation = Quaternion.Euler(t * rotationSpeed, 00);
        transform.localRotation = rotation;
    }
 
    public static float SineFunction(float x, float t)//static을 다른 스크립트에서 접근 가능  
    {
        return Mathf.Sin(Mathf.PI * (x + t));
    }
 
    public static float MultiSineFunction(float x, float t)
    {
        float y = Mathf.Sin(Mathf.PI * (x + t));
        y += Mathf.Sin(2f * Mathf.PI * (x + 0.5f * t))/2f;
        y *= 2f / 3f;
        return y;
    }
}
 
cs



1
2
3
4
using UnityEngine;
 
public delegate float GraphFuction(float x, float t);
 
cs


1
2
3
4
5
6
7
8
9
using UnityEngine;
 
public enum GraphName
{
    Sine,
    MultiSine
}
 
 
cs


Posted by 도이(doi)
,
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
48
49
50
51
52
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Graph : MonoBehaviour
{
    public Transform pointPrefab;
    [Range(10100)] 
    public int resolution = 10//prefab의 개수
    [Range(0.1f, 5)]
    public float height = .5f;
    [Range(150)]
    public float length = 2f;
    [Range(0100)]
    public float rotationSpeed = 50f;
    [Range(.1f, 2f)]
    public float prefabScale = 1f;
    Transform[] points;
 
    private void Awake()
    {
        points = new Transform[resolution]; //배열은 미리 크기를 지정해주어야 한다. 
        for(int i=0; i < points.Length; i++)
        {
            Transform point = Instantiate(pointPrefab);
            point.SetParent(transform, false); //생성자 하위 항목으로 prefab넣기 
            points[i] = point; //points배열에 생성한 point 넣기 
        }
    }
 
    private void Update()
    {
        float step = length / resolution;
        Vector3 scale = Vector3.one * prefabScale;
        for (int i=0; i<points.Length; i++)
        {
            //point wave animation
            Transform point = points[i];
            Vector3 position = point.localPosition; //local position을 변수값으로 가져옴 
            position.x = (i + 0.5f) * step - (length / 2);
            position.y = height * Mathf.Sin(Mathf.PI * (position.x + Time.time)); //x축으로 이동하는 sin파(애니메이션) 파이를 곱한 이유는 주기를 2로 변경하기 위해서  
            position.z = 0;
            point.localPosition = position; //localposition을 수정한 position으로 변경
            point.localScale = scale;
        }
        //x축으로 회전 
        Quaternion rotation = transform.localRotation;
        rotation = Quaternion.Euler(Time.time * rotationSpeed, 00);
        transform.localRotation = rotation;
    }
}
 
cs
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
Shader "Custom/ColoredPoint"
{
    Properties
    {
        _Glossiness ("Smoothness", Range(0,1)) = 1
        _Metallic ("Metallic", Range(0,1)) = 0.0
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 200
 
        CGPROGRAM
        #pragma surface surf Standard fullforwardshadows
        #pragma target 3.0
 
        struct Input
        {
            float3 worldPos; //input값으로 worldPos 사용 
        };
 
        half _Glossiness;
        half _Metallic;
        
        UNITY_INSTANCING_BUFFER_START(Props)
        UNITY_INSTANCING_BUFFER_END(Props)
 
        void surf (Input IN, inout SurfaceOutputStandard o)
        {
            o.Albedo.rg = IN.worldPos.xy * 0.5 + 0.5; //worldPosition에 따라서 색상 가짐 
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = 0.5;
        }
        ENDCG
    }
    FallBack "Diffuse"
}
 
cs


Posted by 도이(doi)
,


요약 정리 

클래스란 무엇인가?

클래스는 컴퓨터 메모리에 있는 객체를 사용할 수 있는 설계도라 생각할 수 있다.
클래스는 객체에 사용할 수 있는 데이터와 기능을 저장한다. 

클래스는 또한, 객체에 속하지 않는 클래스 자체에 속하는 데이터와 기능을 저장할 수 있다.
이는 주로 전역적으로 이용되는 기능을 제공할 때 사용된다. 


접근 한정자(public, private, protected, internal) ?

사진 출처 : https://edmundtips.tistory.com/12

monobehaviour 이란?

게임 오브젝트에 custom behaviour를 프로그래밍하기 위해서 사용된다.
.Net프레임워크의 다중 프레임워크 구현인 Mono프로젝트를 사용함. 
(그래서 이름이 Mono + Behaviour임.)


namespace 란?

코드를 위한 도메인이라고 생각하면 된다. 
namespace는 코드를 조직화하고 이름간의 중복 오류로 인한 충돌을 방지한다.

namespace를 사용하기 위해서 계속 앞에 붙이는 것이 번거롭기에
컴파일러에게 미리 namespace를 찾아두라고 말할 수 있다. 
코드의 맨 앞에 using namespace;의 형태로 사용한다. 


structure란?

structure는 class와 유사하게 설계도의 역할을 합니다. 
다만, class와는 다르게 객체를 생성하는 것이 아닌, 값(정수 혹은 색상)을 생성합니다. 
class와 정의하는 방법이 같습니다. 


const란?

수정하지 않을 값. 필드(객체에서 속성, 변수)일 필요가 없음.
컴파일할 때 계산된다. 숫자와 같은 기본 유형에서만 가능함. 


시계 코드 

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
using System
using UnityEngine;
 
public class Clock : MonoBehaviour 
{
    public Transform hoursTransform, minutesTransform, secondsTransform;
    const float degreesPerHour = 30f;
    const float degreesPerMinute = 6f;
    const float degreesPerSecond = 6f;
 
    public bool Continous; 
 
    private void Update()
    {
        if (Continous)
        {
            ContinousTime();
        }
        else
            DiscreteTime();
    }
 
    //digital적으로 시계추 움직임 
    private void DiscreteTime()
    {
        //시간 데이터 받아오기 
        DateTime time = DateTime.Now;
        //회전 
        hoursTransform.localRotation = Quaternion.Euler(0f, time.Hour * degreesPerHour, 0f);
        minutesTransform.localRotation = Quaternion.Euler(0f, time.Minute * degreesPerMinute, 0f);
        secondsTransform.localRotation = Quaternion.Euler(0f, time.Second * degreesPerSecond, 0f);
    }
 
    //analog적으로 시계추 움직임 
    private void ContinousTime()
    {
        //시간 데이터 받아오기 
        TimeSpan time = DateTime.Now.TimeOfDay;
        //회전 
        hoursTransform.localRotation = Quaternion.Euler(0f, (float)time.TotalHours * degreesPerHour, 0f);
        minutesTransform.localRotation = Quaternion.Euler(0f, (float)time.TotalMinutes * degreesPerMinute, 0f);
        secondsTransform.localRotation = Quaternion.Euler(0f, (float)time.TotalSeconds * degreesPerSecond, 0f);
    }
}
cs

완성된 영상 


관련링크 
https://catlikecoding.com/unity/tutorials/basics/game-objects-and-scripts/


Posted by 도이(doi)
,

Mathf

programming/c# 2018. 11. 17. 14:59
Absf의 절대 값을 구합니다.
Acosf의 호 - 코사인을 반환합니다. 코사인이 f 인 각도를 라디안 단위로 반환합니다.
Approximately

두 개의 부동 소수점 값을 비교하여 유사하면 true를 반환합니다.

AsinReturns the arc-sine of f - the angle in radians whose sine is f.
AtanReturns the arc-tangent of f - the angle in radians whose tangent is f.
Atan2Returns the angle in radians whose Tan is y/x.
Ceil

f보다 크거나 같은 가장 작은 정수를 반환합니다. (올림) - 정수는 float형태

CeilToInt

f보다 크거나 같은 가장 작은 정수를 반환합니다. (올림) - 정수는 int형태

Clamp

최소 float 값과 최대 float 값 사이의 값을 return합니다.

Clamp01Clamps value between 0 and 1 and returns value.
ClosestPowerOfTwoReturns the closest power of two value.
CorrelatedColorTemperatureToRGBConvert a color temperature in Kelvin to RGB color.
CosReturns the cosine of angle f.
DeltaAngleCalculates the shortest difference between two given angles given in degrees.
ExpReturns e raised to the specified power.
Floorf보다 작거나 같은 가장 큰 정수를 구합니다. (내림)
FloorToIntReturns the largest integer smaller to or equal to f.
GammaToLinearSpaceConverts the given value from gamma (sRGB) to linear color space.
InverseLerpCalculates the linear parameter t that produces the interpolant value within the range [a, b].
IsPowerOfTwoReturns true if the value is power of two.
Lerp선형 적으로 a와 b 사이를 t로 보간합니다.
LerpAngleLerp와 동일하지만 값이 360 도로 랩 할 때 값이 올바르게 삽입되는지 확인합니다.
LerpUnclampedLinearly interpolates between a and b by t with no limit to t.
LinearToGammaSpace주어진 값을 선형에서 감마 (sRGB) 색 공간으로 변환합니다.
LogReturns the logarithm of a specified number in a specified base.
Log10Returns the base 10 logarithm of a specified number.
Max

둘 이상의 값 중 가장 큰 값을 반환합니다. (최대값 판별)

Min

둘 이상의 값 중 가장 작은 값을 반환합니다. (최솟값 판별)

MoveTowards값을 타겟쪽으로 이동합니다.
MoveTowardsAngleSame as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
NextPowerOfTwoReturns the next power of two value.
PerlinNoise2D Perlin 노이즈를 생성합니다.
PingPong

PingPongs는 길이 t보다 크지 않고 절대 0보다 작지 않도록 값 t를가집니다.

PowReturns f raised to power p.
RepeatLoops the value t, so that it is never larger than length and never smaller than 0.
Round

가장 가까운 정수로 반올림 한 f를 반환합니다. (반올림)

RoundToInt가장 가까운 정수로 반올림 한 f를 반환합니다. (반올림)
SignReturns the sign of f.
SinReturns the sine of angle f.
SmoothDamp시간이 지남에 따라 원하는 목표를 향해 값을 점차적으로 변경합니다.
SmoothDampAngle시간이 지남에 따라 원하는 목표 각도를 향해도 단위로 주어진 각도를 점차적으로 변경합니다.
SmoothStep

한계에서 스무딩을 사용하여 최소값과 최대 값 사이에 보간합니다.

SqrtReturns square root of f.
TanReturns the tangent of angle f in radians.


Posted by 도이(doi)
,