2017년 2월 21일 화요일

Unity 포물선 운동

포물선 운동


1. Unity Physics


1) 원하는 방향으로의 포물선 운동
1
2
3
4
void SetVelocity(Vector3 velocity)
{
    GetComponent<Rigidbody>().velocity = velocity;
}
cs

또는
1
2
3
4
void SetForce(Vector3 force)
{
    GetComponent<Rigidbody>().AddForce(force, ForceMode.Impulse);
}
cs

2) 원하는 좌표로의 포물선 운동
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Vector3 GetVelocity(Vector3 currentPos, Vector3 targetPos, float initialAngle)
{
    float gravity = Physics.gravity.magnitude;
    float angle = initialAngle * Mathf.Deg2Rad;
 
    Vector3 planarTarget = new Vector3(targetPos.x, 0, targetPos.z);
    Vector3 planarPosition = new Vector3(currentPos.x, 0, currentPos.z);
 
    float distance = Vector3.Distance(planarTarget, planarPosition);
    float yOffset = currentPos.y - targetPos.y;
 
    float initialVelocity = (1 / Mathf.Cos(angle)) * Mathf.Sqrt((0.5f * gravity * Mathf.Pow(distance, 2)) / (distance * Mathf.Tan(angle) + yOffset));
 
    Vector3 velocity = new Vector3(0f, initialVelocity * Mathf.Sin(angle), initialVelocity * Mathf.Cos(angle));
 
    float angleBetweenObjects = Vector3.Angle(Vector3.forward, planarTarget - planarPosition) * (targetPos.x > currentPos.x ? 1 : -1);
    Vector3 finalVelocity = Quaternion.AngleAxis(angleBetweenObjects, Vector3.up) * velocity;
 
    return finalVelocity;
}
cs

Type Identifier Explain
Vector3
currentPos 출발 좌표
Vector3 targetPos 도착 좌표
float initialAngel 포물선의 각도

Example
1
2
3
4
5
void Fire(Vector3 target)
{
    Vector3 velocity = GetVelocity(transform.position, target, 45f);
    SetVelocity(velocity);
}
cs

2. Spline


세개 이상의 좌표를 이용해 포물선을 구현 가능
Curves and Splines
소스 받기

사용 방법
SplineNode 컴퍼넌트가 붙은 오브젝트들을 생성한다.
SplineController 컴퍼넌트를 붙인 오브젝트를 생성한다.
SplineController 컴퍼넌트에 SplineNode 가 붙어있는 오브젝트들을 링크시킨다.