Unity3D/Problems

Unity 포물선 운동 구현 (C#)

일등하이 2016. 10. 21. 14:12
반응형
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
using UnityEngine;
 
using System.Collections;
 
public class ThrowSimulator : MonoBehaviour
 
{
 
    private Transform bullet;   // 포물체
 
    private float tx;
 
    private float ty;
 
    private float tz;
 
    private float v;
 
    public float g = 9.8f;
 
    private float elapsed_time;
 
    public float max_height;
 
    private float t;
 
    private Vector3 start_pos;
 
    private Vector3 end_pos;
 
 
 
    private float dat;  //도착점 도달 시간 
 
    
 
    public void Shoot(Transform bullet, Vector3 startPos, Vector3 endPos, float g, float max_height, System.Action onComplete)
 
    {
 
        start_pos = startPos;
 
        end_pos = endPos;
 
        this.g = g;
 
        this.max_height = max_height;
 
        this.bullet = bullet;
 
        this.bullet.position = start_pos;
 
 
 
        var dh = endPos.y - startPos.y;
 
        var mh = max_height - startPos.y;
 
        ty = Mathf.Sqrt(2 * this.g * mh);
 
 
 
        float a = this.g;
 
        float b = -2 * ty;
 
        float c = 2 * dh;
 
 
 
        dat = (-+ Mathf.Sqrt(b * b - 4 * a * c)) / (2 * a);
 
        
 
        tx = -(startPos.x - endPos.x) / dat;
 
        tz = -(startPos.z - endPos.z) / dat;
 
        
 
        this.elapsed_time = 0;
 
 
 
        StartCoroutine(this.ShootImpl(onComplete));
 
 
 
    }
 
 
 
    IEnumerator ShootImpl(System.Action onComplete)
 
    {
 
        while (true)
 
        {
 
            this.elapsed_time += Time.deltaTime;
 
 
 
            var tx = start_pos.x + this.tx * elapsed_time;
 
            var ty = start_pos.y + this.ty * elapsed_time - 0.5f * g * elapsed_time * elapsed_time;
 
            var tz = start_pos.z + this.tz * elapsed_time;
 
 
 
 
 
            var tpos = new Vector3(tx, ty, tz);
 
 
 
            bullet.transform.LookAt(tpos);
 
 
 
            bullet.transform.position = tpos;
 
 
 
            if (this.elapsed_time >= this.dat)
 
                break;
 
            
 
            yield return null;
 
        }
 
 
 
        onComplete();
 
    }
 
}
 
 
 
출처: https://smilejsu.tistory.com/1036 [{ Unity3D }]
cs







높이보다 시작지점, 끝지점이 낮을경우는 동작 하지 않습니다. 


패키지 첨부 해요 

ThrowSimulation.unitypackage



반응형