A Path Game Like Flight Control

Time to add the plane and make it follow the path the player draws. For this, I added one method to the Path class and added a PathSprite class which takes care of interpolating the path and adjusting to any changed done to the path.

The PathSprite

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
using UnityEngine;
using System.Collections;
 
namespace linepath {
	public class PathSprite : MonoBehaviour {
 
		[HideInInspector]
		public float progress;
 
		protected Path pathController;
		protected float angle = 0;
 
		protected float speed = 0.6f;
		protected float speedOnPath = 0f;
 
		protected float oldLength = 0f;
		protected float oldProgress = 0f;
		protected float maxDistance = 0.8f;
 
		//rotation easing
		protected float dr = 0f;
		protected float ar = 0f;
		protected float vr = 0f;
		protected float targetRotation = 0f;
		protected float rotationSpring = 0.1f;
		protected float rotationDamping = 0.5f;
 
		protected bool collect;
 
 
 
		protected void UpdatePositionAndProgess () {
 
			float iterations = (pathController.totalLength/(speed  * Time.deltaTime));
			speedOnPath = 1/iterations;
 
			if (oldLength != 0 && pathController.totalLength - oldLength > 0.1f) {
 
				progress = (oldLength * oldProgress)/pathController.totalLength;
				pathController.RenderObjectAt( progress );
			}
			oldLength = pathController.totalLength;
			oldProgress = progress;
		}
 
		protected void UpdatePathSprite ()
		{
 
			if (pathController.points.Count <= 1 || progress + speedOnPath >= 1 || pathController.totalLength < 0.1f) {
 
				float angle = transform.eulerAngles.z * Mathf.Deg2Rad;
				var position = transform.position;
				position.x = transform.position.x + speed * Mathf.Cos(angle) * Time.deltaTime;
				position.y = transform.position.y + speed * Mathf.Sin(angle) * Time.deltaTime;
				transform.position = position;
 
			} else {
				//increment progress with our calculated speedOnPath
				//this ensures the plane keeps moving at the speed set in speed variable
				progress += speedOnPath;
 
				if (pathController.points.Count > 1) pathController.RenderObjectAt( progress );
 
				//set target rotation for ease/spring logic bellow
				targetRotation = pathController.angle;
				if (targetRotation > transform.eulerAngles.z + 180) targetRotation -= 360;
				if (targetRotation < transform.eulerAngles.z - 180) targetRotation += 360;
 
				//redraw the line so dashes/dots already transposed by plane are not redrawn. meaning, they are erased.
				oldProgress = progress;
 
				//ease and spring the rotation a bit so it looks nicer!
				dr = targetRotation - transform.eulerAngles.z;
				ar = dr * rotationSpring;
				vr += ar;
				vr *= rotationDamping;
				var rotation = transform.eulerAngles;
				rotation.z += vr;
				transform.eulerAngles = rotation;
			}
		}
	}
}

The UpdatePositionAndProgess changes the amount of change done in each iteration of the interpolation so that the plane appears to be moving always at the same speed, independently of how long or short the current path is.

UpdatePathSprite takes care of the interpolation and smooths the rotation of the sprite. I believe in Unity the transform.Rotate method takes care of wrapping the values but I wanted to apply a damping value to only one axis of the rotation so I did it the old fashion way.

The Plane

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
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using linepath;
 
[RequireComponent (typeof(Path))]
public class Plane : PathSprite {
 
	public Drawing drawingLayer;
 
	private float baseLength = 2f;
	private int dotsInBaseLength = 5;
 
	void Awake ()
	{
		pathController = GetComponent<Path> ();
	}
 
	void FixedUpdate () {
 
		if (pathController.points.Count > 0 ) {
 
			drawingLayer.vertices.Clear();
 
			float numPoints = pathController.totalLength/0.5f;
 
			float progressIncrement = 1/numPoints;
 
			float p = 0.0f;
 
			while (p < 1) {
 
				var point = pathController.GetPointAtProgress(p);
 
				if (point != null && p > progress) {
					drawingLayer.vertices.Add (Camera.main.WorldToScreenPoint(new Vector3(point.x, point.y, 0)));
				}
				p += progressIncrement;
 
			}
 
		}
		UpdatePathSprite ();
	}
 
	public void HandleTouchDown (Vector2 touch)
	{
 
		var point = Camera.main.ScreenToWorldPoint (touch);
 
		if (Vector2.Distance (point, transform.position) < 0.5f) 
		{
			pathController.points.Clear ();
			drawingLayer.vertices.Clear();
			collect = true; 
		}
 
	}
 
	public void HandleTouchMove (Vector2 touch)
	{
 
		var point = Camera.main.ScreenToWorldPoint (touch);
 
 
		if (collect) {
 
			if (pathController.points.Count == 0) {
				progress = 0f;
				List<Vector2> ps = new List<Vector2> ();
				ps.Add ( (Vector2) transform.localPosition);
				pathController.InsertMultiplePoints (ps, 0);
			} else {
 
				Vector2 lastPoint = pathController.points [pathController.points.Count - 1].point;
 
				if (Vector2.Distance (point, lastPoint) > maxDistance) {
					pathController.AppendPoint ( (Vector2) point);
					UpdatePositionAndProgess ();
				}
 
			}
		} 
	}
 
 
	public void HandleTouchUp (Vector2 touch)
	{
		collect = false;
	}
 
	void DrawPath ()
	{
 
		drawingLayer.vertices.Clear();
 
		float numPoints = pathController.totalLength/0.5f;
 
		float progressIncrement = 1/numPoints;
 
		float p = 0.0f;
 
		while (p < 1) {
 
			var point = pathController.GetPointAtProgress(p);
 
			if (point != null && p > progress) {//
				Debug.Log(point.x);
				drawingLayer.vertices.Add (Camera.main.WorldToScreenPoint(new Vector3(point.x, point.y, 0)));
 
			}
 
			p += progressIncrement;
		}
	}	
}

The Plane extends PathSprite and handles input from the user determining when to collect points to the path or not.

The New Path Class

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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
 
namespace linepath {
 
	public class Path : MonoBehaviour {
 
		[HideInInspector]
		public float angle;
		[HideInInspector]
		public float totalLength;
		[HideInInspector]
		public List<PathPoint> points;
 
		private PathPoint first;
 
		void Awake () {
			points = new List<PathPoint>();
			totalLength = 0f;
			angle = 0f;
		}
 
 
		public void AppendPoint (Vector2 point) {
			InsertPoint(point, points.Count, false);
		}
 
		public void InsertMultiplePoints(List<Vector2> points, int index) {
			int len = points.Count;
			for (int i = 0; i < len; i++) {
				InsertPoint(points[i], index + i, true);
			}
		}
 
		public PathPoint GetPointAtProgress (float progress) {
 
			progress = Mathf.Abs(progress);
 
			PathPoint point = new PathPoint (0, 0);
			if (progress > 1) progress = 1;
			PathPoint pp = first;
			if (pp == null || pp.next == null) return null;
			if (pp.next.progress < 0) return null;
 
			while (pp.next != null && pp.next.progress < progress) {
				pp = pp.next;
			}
 
			if (pp != null) {
				angle = pp.angle;
				if (pp.length == 0) return null;
				float pathProg = (progress - pp.progress) / (pp.length / totalLength);
				point.x = pp.x + pathProg * pp.xChange;
				point.y = pp.y + pathProg * pp.yChange;
				return point;
 
			}
			return null;
		}
 
		public void RenderObjectAt( float progress) {
 
			if (progress > 1) {
				progress -= (int) progress;
			} else if (progress < 0) {
				progress -= (int) progress - 1;
			}
 
			if (first == null) {
				return;
			}
 
			PathPoint pp = first;
			while (pp.next != null && pp.next.progress < progress) {
				pp = pp.next;
			}
 
			if (pp != null) {
				angle = pp.angle;
				if (pp.length == 0 || totalLength == 0) return;
				float pathProg = (progress - pp.progress) / (pp.length / totalLength);
				float px = pp.x + pathProg * pp.xChange;
				float py = pp.y + pathProg * pp.yChange;
				transform.localPosition = new Vector3(px, py, 0);
			}
		}
 
		public void Dispose () {
			points.Clear();
		}
 
 
		public void SetPoints(List<Vector2> value) {
 
			points.Clear();
			InsertMultiplePoints(value, 0);
		}
 
 
		private void InsertPoint(Vector2 point, int index, bool skipOrganize)  {
 
			PathPoint p = new PathPoint (0,0);
			p.SetPoint(point);
 
			if (points.Count == 0) {
				points.Add(p);
			} else {
				points.Insert(index, p);
			}
 
			if (!skipOrganize) {
				Organize();
			}
		}
 
		private void Organize() {
 
			totalLength = 0;
			int last = points.Count - 1;
 
			if (last == -1) {
				first = null;
			} else if (last == 0) {
				first = points[0];
				first.progress = first.xChange = first.yChange = first.length = 0;
				return;
			}
			PathPoint pp = null;
			for (int i = 0; i <= last; i++) { 
				if (points[i] != null) {
					pp = points[i];
					if (i == last) {
						pp.length = 0;
						pp.next = null;
					} else {
						pp.next = points[i + 1];
 
						pp.xChange = pp.next.x - pp.x;
						pp.yChange = pp.next.y - pp.y;
						pp.length = (float) Mathf.Sqrt(pp.xChange * pp.xChange + pp.yChange * pp.yChange);
						totalLength += pp.length;
					}
				}
			}
			first = pp = points[0];
			float curTotal = 0f;
			while (pp != null) {
				pp.progress = curTotal / totalLength;
				curTotal += pp.length;
				pp = pp.next;
			}
 
 
			UpdateAngles();
		}
 
		private void UpdateAngles() {
			PathPoint pp = first;
			while (pp != null) {
				pp.angle = (float) Mathf.Atan2(pp.yChange, pp.xChange ) * Mathf.Rad2Deg;
				pp = pp.next;
			}
		}
 
	}
}

And the new method add to the Path class is the RenderObjectAt method. It updates its transform.

And that’s it. Run the game and see how it handles.

You can download the source here.