Showing posts with label 2D. Show all posts
Showing posts with label 2D. Show all posts

Sunday, 4 March 2018

2D Dynamic water with refraction effect.

I was always curious about how to get that distorted effect you see on water surfaces, which is something I have recently learnt how to do in OpenGL. I managed to create a water surface from scratch which can reflect and refract the environment.

I now want to try a similar experiment in unity: water, which can refract objects behind it.
Additionally, we are going to make the water dynamic using a similar method we use in the "Perlin noise for ocean waves post".

First thing first, create an empty GameObject and add these components to it: a script called "Water2D", a MeshFilter, a MeshRenderer and an EdgeCollider2D.

Then create a material. You can call it whatever you want of course, "Water_Refractive" sounds ok to me. You can leave the standard shader for now as we will firstly get the mesh to work properly and then we will apply a refractive shader. Assign the material to the MeshRenderer of our GameObject:



Part 1: dynamic mesh generation

The mesh is going to be re-created every frame. Certainly not the best approach if performance is your priority, but this will allow us to change the number of vertices during runtime, which is what I wanted. The script, previously added to the GameObject, called "Water2D", looks like this:


  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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Water2D : MonoBehaviour {

 public int topVerticesCount = 10;
 public float waterHeight = 10;
 public float waterSpeed = 1;
 public float density = 50;
 public float amplitude = 5;

 Mesh mesh;
 MeshFilter m_filter;
 EdgeCollider2D m_collider;
 List<Vector3> topVertices;

 void Start () {

  topVertices = new List<Vector3> ();
  m_filter = GetComponent<MeshFilter> ();
  m_collider = GetComponent<EdgeCollider2D> ();
  mesh = new Mesh ();
 
 } 

 void Update () {

  UpdateTop ();
  GenerateMesh ();

 }

 void GenerateMesh()
 {
  List<Vector3> meshVertices = new List<Vector3>();
  List<Vector3> bottomVertices = new List<Vector3>();

  List<int> meshTriangles = new List<int>();
  List<Vector2> meshUVs = new List<Vector2> ();

  //Add bottom vertices
  for (int i = 0; i < topVerticesCount; i++) {

   float y = topVertices [i].y + waterHeight;

   bottomVertices.Add (new Vector3 (topVertices [i].x,topVertices [i].y - y,topVertices [i].z));  
  
  } 

  int totalVertivesCount = topVertices.Count + bottomVertices.Count;
  int totalTriangles = totalVertivesCount - 2;

  for (int i = 0; i < totalTriangles/2; i++) {
  
   meshVertices.Add (topVertices [i]);
   meshUVs.Add (new Vector2 ((float)i/topVerticesCount, 1.0f));

   meshVertices.Add (bottomVertices [i+1]);
   meshUVs.Add (new Vector2 ((float)(i+1)/topVerticesCount, 0.0f));

   meshVertices.Add (bottomVertices [i]);
   meshUVs.Add (new Vector2 ((float)i/topVerticesCount, 0.0f));


   meshVertices.Add (topVertices [i]);
   meshUVs.Add (new Vector2 ((float)i/topVerticesCount, 1.0f));

   meshVertices.Add (topVertices [i+1]);
   meshUVs.Add (new Vector2 ((float)(i+1)/topVerticesCount, 1.0f));

   meshVertices.Add (bottomVertices [i+1]);
   meshUVs.Add (new Vector2 ((float)(i+1)/topVerticesCount, 0.0f));
  
  }

  for (int i = 0; i < meshVertices.Count; i++)
   meshTriangles.Add (i);

  mesh.vertices = meshVertices.ToArray ();
  mesh.triangles = meshTriangles.ToArray ();
  mesh.uv = meshUVs.ToArray ();

  mesh.RecalculateBounds ();
  mesh.RecalculateNormals ();
  mesh.RecalculateTangents();
  m_filter.mesh = mesh;

 

 }

 void UpdateTop()
 {

  //Generate top vertices
  topVertices.Clear ();
  if (topVerticesCount < 2)
   topVerticesCount = 2;
  for (float i = 0; i < topVerticesCount; i++) {
   float y =amplitude *  Mathf.PerlinNoise ((i + Time.time * waterSpeed) / density, (i + Time.time * waterSpeed) / density);
   topVertices.Add (new Vector3 (i, y, 0));
  }

  //Update edge collider
  Vector2[] paths = new Vector2[topVertices.Count];

  for (int i = 0; i < paths.Length; i++)
   paths [i] = new Vector2 (topVertices [i].x, topVertices [i].y);

  m_collider.points = paths;
 }
}

If you are not familiar with meshes and how to create them there are plenty of tutorials online, especially on the official Unity website. To give you a quick crash course, a mesh is a collection of vertices and triangles which are drawn using those vertices. In this approach, I firstly create a line of horizontal vertices (which i called "topVertices"). The minimum amount for the top vertices is 2 of course (line 98 - 99). I then apply Perlin noise to the y parameter of each vertex in order to get them to wave (lines 100 - 103). The edge collider is also updated according to these vertices so objects can collide with the waves.

In the GenerateMesh method I simply "triangulate" the vertices: I create a "bottom vertex" for each "top vertex" and create triangles. The bottom vertices are placed at a certain distance from their respective top vertices. This distance is a public parameter (waterHeight)which basically determines the water height.

If you apply a basic color to the material and press play, you should see this:


Part 1: refraction effect

Indeed, it's shader writing time.

To create the refraction effect I used a special type of map called DUDV map. If you perform a quick google search for it you will find many of these maps to download. Save one and import it as a new asset.

Also, before proceeding, create a simple sprite and place it in the scene. Any image will do, we'll use it to show the refraction effect. I used one of the available sprites in Unity and tinted it red:




At this point, the shader itself. The code is very much based on the "Glass effect shader", which can be found here. I modified just enough to use the map I wanted to and added parameters for altering the effect.



  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
Shader "FX/Custom Water Distortion" {
Properties {
 _Color ("Tint", Color) = (1,1,1,1)
 _DistortionStrength  ("Distortion", range (0,15)) = 1
 _DistortionSpeedX  ("Distortion Speed X", range (-5,5)) = 0
 _DistortionSpeedY  ("Distortion Speed Y", range (-5,5)) = 0
 _MainTextureSpeedX  ("Main texture speed X", range (-10,10)) = 0
 _MainTextureSpeedY  ("Main texture speed Y", range (-10,10)) = 0
 _MainText("Main texture",2D) = "white"{} 
 _DistMap ("Distortion map", 2D) = "white" {}
}

Category {
 
 Tags { "Queue"="Transparent" "RenderType"="Opaque" }

 SubShader {

  //Create a texture with all that is on the screen behin our mesh.
  // This texture is accessible via the parameter _GrabTexture
  GrabPass {       
   Name "BASE"  
   }
  
  Pass {
   Name "BASE"
   Tags { "LightMode" = "Always" }
   
CGPROGRAM
#pragma vertex vert
#pragma fragment frag

#include "UnityCG.cginc"

struct appdata_t {
 float4 vertex : POSITION;
 float2 texcoord: TEXCOORD0;
};

struct v2f {
 float4 vertex : POSITION;
 float4 uvgrab : TEXCOORD0;
 float2 uvdist : TEXCOORD1;
 float2 uvmain : TEXCOORD2;
};

float _DistortionStrength;
float _MainTextureSpeedX;
float _MainTextureSpeedY;

float4 _DistMap_ST;
float4 _MainText_ST;
float4 _Color;

v2f vert (appdata_t v)
{
 v2f o;
 o.vertex = UnityObjectToClipPos(v.vertex);
 #if UNITY_UV_STARTS_AT_TOP
 float scale = -1.0;
 #else
 float scale = 1.0;
 #endif
 o.uvgrab.xy = (float2(o.vertex.x, o.vertex.y * scale) + o.vertex.w) * 0.5;
 o.uvgrab.zw = o.vertex.zw;
 o.uvdist = TRANSFORM_TEX( v.texcoord, _DistMap );
 o.uvmain = TRANSFORM_TEX( v.texcoord, _MainText );
 return o;
}

sampler2D _GrabTexture;
float4 _GrabTexture_TexelSize;
float _DistortionSpeedX;
float _DistortionSpeedY;
sampler2D _DistMap;
sampler2D _MainText;

float4 frag( v2f i ) : COLOR
{
 // Distortion map sampling. 
 half2 dist = tex2D(_DistMap, float2(i.uvdist.x + _Time.x*_DistortionSpeedX,i.uvdist.y - _Time.x*_DistortionSpeedY)).rg; 
 float2 offset = dist * _DistortionStrength * _GrabTexture_TexelSize.xy ;

 //Apply distortion to the grab texture by modifying the uv coordinates
 i.uvgrab.xy = offset * i.uvgrab.z + i.uvgrab.xy;
  
 float4 col = tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(i.uvgrab)); 
 float4 mainColor = tex2D(_MainText,float2(i.uvmain.x + _Time.x * _MainTextureSpeedX,i.uvmain.y + _Time.x *_MainTextureSpeedY));

 return col * _Color * mainColor;
}
ENDCG
  }
 }



}

}

Simply described, the shader samples the distortion map, which represents a series of two dimensional vectors and creates an offset (using those vector 2) which is used to then sample the _GrabTexture (line 81 - 87). This is how the refraction effect is created.

This shader has parameters that let you move the textures and increase or decrease the distortion effect. Also, you can apply a normal texture if you want to.

Apply the shader to the material and this is the final result:



Conclusion

Water effect with refraction. A nice effect to add to your 2D game.
Remember, collisions are also updated, which means that objects can collide with your water. Specifically, with the top of the water, as we used an EdgeCollider.

If you place an object in the scene, with a 2D collider and a rigidbody, you should see it colliding with the water:




Tuesday, 9 January 2018

Tilemap: custom brush for prefabs.

Finally, a new post.

I haven't been using Unity much recently as I got sucked into OpenGL development, however, with the recent updates that came to Unity I was drawn back to it.

Being a big fan of 2D, I was excited to see the new features added, in particular, the tilemap system: a very easy and fast way to lay out 2D maps and create levels.

I then started messing around with custom brushes and I came up with a slightly modified version of the prefab brush that is provided in this tutorial project. I modified the PrefabBrush script in order to be able to select different "prefab palettes" and display the preview in the scene editor.

Also, for this tutorial I re-used this asset you have seen before.

To set it up, I created 4 prefabs in 2 different folders "Collectibles" and "Enemies". I have a "Coin" and a "Heart" prefab in the "Collectibles" folder and a "Slime" and "Bat" prefab in the "Enemies" folder. These prefabs are going to be GameObjects that we will place in the scene using the brush we are creating. The brush will allow you to choose which prefab palette you wish to use and iterate through the GameObjects of that particular palette.

Firstly we need to create the template for the prefab palette: it does not get any easier that this script down here:


[CreateAssetMenu]
public class PrefabPalette : ScriptableObject {
 public GameObject[] prefabs;

}

I kid you not, that is all you need.

This script will enable you to create an asset, which is really a file in which you can place your prefabs:



You can now create 2 prefab palettes, one for the enemies, one for the collectables.

We can now take a look at the PrefabBrush script. I will highlight the modifications I made. It is important to notice how the script is placed inside a folder called "Editor", that is because it incorporates editor scripting as well and it must be inside that folder.


  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


namespace UnityEditor
{
 [CreateAssetMenu]
 [CustomGridBrush(false, true, false, "Prefab Brush")]
 public class PrefabBrush : GridBrush
 {

  public PrefabPalette prefabPalette;

  [HideInInspector] public int index = 0;

  public override void Paint(GridLayout grid, GameObject brushTarget, Vector3Int position)
  {   

   GameObject prefab = prefabPalette.prefabs[index];
   GameObject instance = (GameObject) PrefabUtility.InstantiatePrefab(prefab);
   Undo.RegisterCreatedObjectUndo((Object)instance, "Paint Prefabs");
   if (instance != null)
   {
    instance.transform.SetParent(brushTarget.transform);
    instance.transform.position = grid.LocalToWorld(grid.CellToLocalInterpolated(new Vector3Int(position.x, position.y,0) + new Vector3(.5f, .5f, .5f)));
   
   }
  }

  public override void Erase(GridLayout grid, GameObject brushTarget, Vector3Int position)
  {
   // Do not allow editing palettes
   if (brushTarget.layer == 31)
    return;

   Transform erased = GetObjectInCell(grid, brushTarget.transform, new Vector3Int(position.x, position.y, position.z));
   if (erased != null)
    Undo.DestroyObjectImmediate(erased.gameObject);
  }

  private static Transform GetObjectInCell(GridLayout grid, Transform parent, Vector3Int position)
  {
   int childCount = parent.childCount;
   Vector3 min = grid.LocalToWorld(grid.CellToLocalInterpolated(position));
   Vector3 max = grid.LocalToWorld(grid.CellToLocalInterpolated(position + Vector3Int.one));
   Bounds bounds = new Bounds((max + min)*.5f, max - min);

   for (int i = 0; i < childCount; i++)
   {
    Transform child = parent.GetChild(i);
    if (bounds.Contains(child.position))
     return child;
   }
   return null;
  }
 
 }

 [CustomEditor(typeof(PrefabBrush))]
 public class PrefabBrushEditor : GridBrushEditor
 {
  private PrefabBrush prefabBrush { get { return target as PrefabBrush; } }
   
  GameObject holder;

  public override void OnMouseLeave ()
  {
   base.OnMouseLeave (); 

   if(holder)
    DestroyImmediate (holder);
  }

 
  public override void OnPaintSceneGUI (GridLayout gridLayout, GameObject brushTarget, BoundsInt position, GridBrushBase.Tool tool, bool executing)
  {

   base.OnPaintSceneGUI (gridLayout, null,position, tool, executing); 

   Event e = Event.current;

   if (e.type == EventType.KeyDown && e.keyCode == KeyCode.C) {
    //Debug.Log ("Click, index " + prefabBrush.index);

    prefabBrush.index++;
    if (prefabBrush.index == prefabBrush.prefabPalette.prefabs.Length)
     prefabBrush.index = 0;

    DestroyImmediate (holder);
    holder = Instantiate (prefabBrush.prefabPalette.prefabs [prefabBrush.index]);

   }

   if (!holder)
    holder = Instantiate (prefabBrush.prefabPalette.prefabs [prefabBrush.index]);

   holder.transform.position = position.position + new Vector3(.5f,0.5f,0.0f);

  }  

 }
}

Up to line 53 is the "normal" script, the actual PrefabBrush class. From line 53 onward is the custom editor script.

The PrefabBrush class is pretty much the same as it was in the original script. The method Pain is overridden in order to instantiate the currently selected prefab. This prefab is chosen according to an int value, which is the index of the array of GameObjects found in the PrefabPalette public object. The other 2 methods are straight from the original script and override erase functionality in order to delete the instantiated prefab rather than the underneath tiles that might be present in the tilemap.

The custom editor part is where I put my hands mostly. In order to show the "preview" of the prefab in the scene editor I used a trick: I instantiate an object of the selected prefab (the object holder in the script) and I constantly update its position. OnMouseLeave is called whenever the mouse leaves the editor window. In this method, I delete the holder gameobject so it is no longer present in the scene.

The method OnPaintSceneGUI is continuously called as long as the mouse is in the scene editor window. Here I do a couple of things: I check that the key "C" is pressed: if so, the value of index is incremented (and checked for boundaries), so the prefab will change. If that occurs, I delete the current holder and I create a new one with the new selected prefab from the prefab palette.

I also create a holder object anyway (line 90-91), as the "preview" of the GameObject must be present even if the key "C" is not pressed. I finally update the position of the holder object to follow the value of position which is the cell in the tilemap the mouse is currently hovering on.

At this point, we simply need to create a Prefab Brush object in the project folder and it will then be available in the Tile Palette window:




We can then select the prefab palette we created and start placing prefabs!






Conclusion

The new tilemap feature is fantastic if you are planning to create a 2D game and quickly need to draft levels.

It is important to remember:

- Always separate different tiles/prefabs in different tilemaps: just like in the example above, enemies prefabs are placed in a different tilamap than collectibles.

- Make sure to select the actual tilemap you wish to draw on in the Tile Palette window:


It's easy to forget that and place all the tiles/prefabs in one single tilemap.

- Check the tool you are using: occasionally, the "erase" tool remains selected and it's easy to get confused on "why is it not painting??". Silly mistakes, but can happen.

Tuesday, 2 May 2017

Animation sequence

I have been trying for a while now to create a sequence of animation. By that I mean a chain of animations that play without the user input. Very much like a cutscene or a tutorial, that can be played out to the user without interaction.

After looking up for tutorials I couldn't find anything relevant, so I came up with my own implementation.

I have also played around with the Unity Timeline feature, which is still in experimental mode, and while I was able to create some sequences, I still could not play animations the way I wanted, such as, having the player character move around, shoot, jump and do other things.

In the end I found a solution which, although not optimal, works pretty well and allows me to create scripted animations for each GameObject in the current scene.

I'm still using this  assent, just like the previous posts.

The way I had it in my mind was to have all my sequences as asset files, which I could then plug int a sequence player in the scene.

Firstly, let's take a look at the Sequence script:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public abstract class Sequence :  ScriptableObject {

 public bool playOnce;
 public bool hasBeenPlayed = false;
 public abstract void OnSequenceEnd();
 public abstract IEnumerator sequence(GameObject[] actors);

 protected void CloseAllDialogs(GameObject[] actors)
 {
  for(int i=0; i<actors.Length;i++)
  {
   actors [i].GetComponent<Speak> ().CloseComic ();
  }
 }

}

This is nothing but a base class which will use to create our sequences asset files. As you can see, it's a ScriptableObject, which allows us to create an asset out of it.

The animation sequence itself is going to be a coroutine, which is the IEnumerator on line 6, which will be differet for each animation sequence we wish to write.

The CloseAllDialogs method is strictly related to my current project and should not be relevant for this example.

One limitation I had to work around was the inability of ScriptableObjects to reference objects in the scene. It would have been much easier and neat to have all the GameObjects I wanted to animate in my ScriptableObject file, but that is simply not possible. Instead, the SequencePlayer will be able to "select" objects form the scene and pass them to the scriptable object, and that is the actors GameObject array you see being passed to our co routine on line 6.

This is the SequencePlayer script:

 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
public class SequencePlayer : Interactable {

 public GameObject[] actors;
 public Sequence sequence;
 public bool playOnAwake = false;
 public bool playOnCollision = false;
 public float startDelay = 0;

 void Start()
 {
  if (playOnAwake)
   Invoke ("PlaySequence", startDelay);
 
 }

 public void PlaySequence()
 {

   GameController.instance.currentLevel.SetCurrentState (new PlayableLevel_ConversationState ());
  StartCoroutine (sequence.sequence (actors)); 
 
 }

 override public void OnInteract()
 {
  if (playOnCollision) {
  
   Invoke ("PlaySequence", startDelay);
   GetComponent<Collider2D> ().enabled = false;
  
  }
 }

}

This is, in fact, a Monobehavior script. You can see it inherits from a class called Interactable, which is simply a base class I'm using in my project that represents objects that can interact with the player.

This script will be placed on an empty GameObject in the scene, which should have a collider attached to detect the presence of the player character. I decided to do it this way because I want my animations to be triggered by two main factors: either the scene starts or the player has interacted with our SequencePlayer GameObject, which means has reached an area where an animation sequence should be played.

The 2 bool variables on line 5 and 6 determine which one is the trigger method. If the sequence should be played on awake, as soon as the script is initialized the animation is triggered, with a delay if necessary (line 12). Otherwise, will be triggered once the collision has been detected (line 24 - 31).

The GameObject array actors will need to be pre filled with all the objects we wish to animate. This array is then passed to our ScriptableObject sequence, which is going to do all the magic for us.

Let's have a quick look at our scene now:


We only have the player character on the right. At the moment it is off camera, in our animation we will have it walking in the viewport, greet the player and leave.

An empty GameObject is present in the scene, called Sequencer, and has the SequencePlayer script attached. The inspector will look like this:


As you can see, I passed the Player object to the actors array, and I plugged a Sequence file called ExmapleSequence into the Sequence public field (which is a ScriptableObject).

This is the ExampleSequence scriptable object:

 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
[CreateAssetMenu(fileName="ExampleSequence",menuName="AnimationSequence/ExampleSequence")]
public class ExampleSequence : Sequence {

 override public IEnumerator sequence(GameObject[] actors)
 {
  GameObject playerObj = actors [0];

  playerObj.GetComponent<Rigidbody2D> ().isKinematic = false;

  while (playerObj.transform.position.x < 0) {
   playerObj.GetComponent<CharController> ().Movement (new Vector2 (1, 0));

   yield return null;
  }

  playerObj.GetComponent<CharController> ().Movement (new Vector2 (0, 0));

  yield return new WaitForSeconds (2);

  playerObj.GetComponent<Speak> ().Say ("Greetings!");

  yield return new WaitForSeconds (2);

  playerObj.GetComponent<Speak> ().CloseComic ();

  while (playerObj.transform.position.x >-15) {
   playerObj.GetComponent<CharController> ().Movement (new Vector2 (-1, 0));

   yield return null;
  } 

  OnSequenceEnd ();

 }

 override public void OnSequenceEnd()
 {
  //Currently not used
 }

}

The very first line is used to create the actual asset file. In the editor, if we now navigate to Asset->Create we can see our ExampleSequence asset, which can be instantiated as an asset file in our project folder:


Then, we proceed creating the actual sequence, in the IEnumerator.

In order to move the character around and speak I have created a character controller script, which I am not going to display here as it is quite extensive. However, there are many tutorials on how to create a character controller, but really it's just a script that enables our character movement and apply animations through an AnimatorController.

On line 6 we grab the reference to our player object.

We then proceed to set its RigidBody2D to respond to physics. The while loop will call the Movement(,,,) method of the CharController script which simply moves the object to a certain point, checking the X value of the position. This method also applies animation with the AnimatioController whithin the CharController script.

We then stop the movement (line 16), we wait for a couple of seconds and we get the player to "say" something. This is done very simply with the use of a Canvas in world space. Finally, we close the comic and send the player back the way he came.

And that is it.

This what it looks like in the end:


Clearly, this is not optimized. Each time we need to grab components from the player object, and that is not ideal. To improve on this, we could cache all the components at the beginning of the script and call them accordingly. For this example, this is acceptable.

Conclusion

This simple method is a good starting point to create scripted animations. It can be a little time consuming having to write a complete sequence, but it allows for great control over all the objects we wish to animate. I'm also using this technique to create tutorial sequences for the player, in which the animation sequence is not controller by time, rather, by the user input this time. Before proceeding to the next instruction, instead of using WaitForSeconds(..) we can pass in a while loop, like so:

1
2
3
   do {
    yield return null;
   } while (!Input.GetMouseButtonDown (0));

This way, the script will resume only after the user has tapped the screen.

I think a lot can be done to optimize the scripts, however, depending on your project, this could be a decent solution for cutscenes and scripted animations.

Monday, 5 September 2016

Sprite depth for top down 2D

This is going to be a very short and quick post about sprites in Unity.
I discovered a nice simple trick on how to dynamically change the depth of a sprite for top down 2D games. For this project, I used this asset and the character comes from here.

Imagine you have your player character roaming around the game. If you simply place the sprites in the scene, they should automatically be set to the same Sorting Layer, and therefore, this should happen:



There is no depth whatsoever, the player is constantly drawn behind the trees, which is fine when he is walking "behind" them, but it looks just wrong when he is in front of them.

Of course, changing the player's sorting layer won't make any difference:


I therefore had to write a very simple script which allows the sprites to dynamically change their sorting layer according to their position.

This is DynamicSortingLayer script:


 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
public class DynamicSortingLayer : MonoBehaviour {

 public float yOffset;

 public float by;

 float layer;

 SpriteRenderer rend;

 Vector3 centerBottom;

 // Use this for initialization
 void Start () {
  
  rend = GetComponent<SpriteRenderer> (); 
 }
 

 void Update () {

  centerBottom = transform.TransformPoint(rend.sprite.bounds.min);

  layer = centerBottom.y + yOffset;

  rend.sortingOrder = -(int)(layer * 100);
 
 }
}

The sorting layer is assigned depending on the position of the sprite, however, when we get the position of the object we usually get its anchor position, which is normally its center. In this case, we want to get the position of the bottom of a sprite. For example, for our player, we want to assign the layer according to its feet Y position, because that's the point which determines whether he is in front or behind the trees.

That's what we do on line 22, we get the bottom-centre points of the sprite and store it into centerBottom. After adding an offset value to it (for minor adjustments), we multiply the Y value position for 100, in order to preserve decimal numbers as we are going to cast it as an int value. Of course, we also need to negate the final value, as we want the sprite at the lowest part of the screen (with lower Y value) to be in front of the other ones and they therefore need a higher value of sorting layer.

This is the final result:


Conclusion

A very quick tutorial on how to create depth in a 2D world. To optimize the script you could separate moving objects from static ones. For, example, the trees do not need the get the sorting layer constantly reassigned as they are not moving. You could assign the sorting layer once in the Start method and leave the Update empty. The player, however, will need to continuously change its sorting layer to ensure it will be drawn correctly in the scene. I placed some colliders onto our objects and put together a simple scene which you can try the WebGL version here.


Thursday, 4 August 2016

Pathfinding part 2: the map editor

This post is a sort of follow up of the previous one. I thought I would show you how I created the simple level editor to layout the map I used for the path finding tutorial.

This will involve editor scripting and, although is very simple, is a good demonstration on how we can manipulate the Unity editor to improve workflow and create tools.

Obviously, every project is different and will require a different approach. For my particular case, I needed to create a tile map which could be made of 3 different types of tiles: grass, sand and wall. I didn't want to start from an empty map, so the way I did it was to create an initial map of a certain size of all grass tiles and then place the sand and wall tiles. That was my idea and that is what I'm going to show you.

By creating a map editor we can then create many more maps very quickly without having to place each tile prefab one by one, which can be very time consuming.

There are 2 main scripts for this project: one is the Map script, which is the one that featured the GeneratePath method we saw in the last post. This script will only be in charge of laying out the tiles and it's the script we will reference in the second script: MapEditor. This simply overrides the inspector for the Map script and is in charge of all the editor stuff.

Before I show you the scripts, I will display a picture of the inspector:

Fig 1

I highlighted to sections of the inspector with 2 different colors for a reason you will see shortly.

So, this is the MapEditor script:

 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
[CustomEditor(typeof(Map))]
public class MapEditor : Editor
{
 Ray r;
 RaycastHit hit;
 bool md = false;

 string[] tiles = { "Grass", "Sand", "Wall" };
 int ind = 0;

 public override void OnInspectorGUI()
 {
  Map map = (Map)target;
  DrawDefaultInspector ();

  if (GUILayout.Button ("Generate MAp")) {
   map.GenerateMap (); 
   //SerializedObject obj = new SerializedObject(map.ti
  }
   
  ind = EditorGUILayout.Popup ("Choose Tile",ind,tiles);
 }

 void OnSceneGUI()
 {

  int controlID = GUIUtility.GetControlID (FocusType.Passive);

  r = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
 
  if (Physics.Raycast (r, out hit, 100, LayerMask.GetMask ("Tile"))) {
   
   
   if (Event.current.type == EventType.mouseDown) {
    GUIUtility.hotControl = controlID;
    md = true;

   }

   if(md)
    hit.collider.gameObject.GetComponent<Tile> ().ChangeType (ind);

  }

  if (Event.current.isMouse && Event.current.type == EventType.MouseUp) {
   GUIUtility.hotControl = 0;
   md = false;
  }


 }


}

Some of the code has been already explained in a previous post I made related to custom inspector. Line 1 and the inheritance from Editor on line 2 are necessary when creating a custom inspector.

Let's focus on the 2 methods in the script.

OnInspectorGui is overridden in order to draw a new inspector. Firstly, we get a reference to the script we want to redraw the inspector for, which is the Map script. The target variable is a built in variable that represents a reference to the object, which needs to be casted accordingly (line 13).

Then we draw the default inspector (line 14), which will display all the public variables that are highlighted in the yellow rectangle in Fig 1. And that's what DrawDefaultInspector() does, simply displays the inspector you would expect to see if you were not overriding it.

It is important to point out that, if you decide to override the drawing process with the method OnIspectorGui(), you MUST call the DrawDefaultInspector() function. If you omit that, this is what you will get:


You'll get nothing. Once you override that method, all the inspector drawing is handled to you.

Going back to the script, on line 16 I created a button which will be displayed in the inspector. By pressing the button, the GenerateMap() method in the Map script is called, which we are going to analyze next.

After that, on line 21 I created a pop up field which will let the user choose what tile to place. these 2 elements (button and pop up field) are visible in Fig 1 in the red rectangle.

The EditorGUILayout.Popup method will return an integer that represents the index of the item selected. As for the lists of selectable items, we pass an array of strings as parameter.

Before move to the next part, OnSceneGui(), let's quickly have a look at the GenerateMap() function in the Map script. I won't post the whole script as there are other things that are unrelated to our purpose, so let's see the method only.


 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
 public void GenerateMap()
    {
  tileParent = new GameObject("Tiles");
  tiles = new GameObject[mapWidth, mapHeight];
  tilescale = grassPrefab.transform.localScale.x;
  levelEditorMap = new int[mapWidth, mapHeight];

  for (int x = 0; x < mapWidth; x++)
  {
   for (int y = 0; y < mapHeight; y++)
   {
    levelEditorMap[x, y] = (int)Tiles.GRASS;
   }
  }

        GameObject g = null;

        for (int x = 0; x < mapWidth; x++)
        {
            for (int y = 0; y < mapHeight; y++)
            {

  currentPosition = new Vector3(startingPosition.x + (float)(x * (tilescale + 0.05f)) , startingPosition.y + (float)(y * (tilescale + 0.05f)), 0);
  g = Instantiate (grassPrefab, currentPosition, Quaternion.identity) as GameObject;
  g.GetComponent<Tile> ().type = (int)Tiles.GRASS;
  g.transform.SetParent(tileParent.transform);
                g.GetComponent<Tile>().arrayX = x;
                g.GetComponent<Tile>().arrayY= y;
                g.GetComponent<Tile>().mapReferece = this;
  tiles[x, y] = g;

              
            }
           
        }
  Debug.Log ("Length now is " + tiles.Length);
  GeneratePathGraph ();
    
    }

I initialize all the objects I need first, and I iterate through the 2 dimensional array levelEditorMap and initialize each element to a grass type tile. The tileParent object is just a parent object for all the tiles that we are going to spawn when generating the map. The other 2 dimensional array tiles will contain the actual gameobjects, the "physical" tiles we see in the scene, whereas levelEditorMap is the "logical" part. Honestly, there is really no need to separate the two, but that's how the path generation logic was set up previously so I left it as it is.

From line 18 to 35 is where the generation occurs. the position of each tile is represented by the Vector3 currentPosition. For both X and Y axis I added a little offset of 0.05 which will place a little space in between the tiles so they can be easily distinguished from each other. Other thatn that, all I do is to instantiate a grassPrefab (a simple quad colored green), assign some references to the Tile script of each instantiated grass prefab clone and that's it. Simple enough.

This is what you will see once you press the "Generate Map" button:


You can see the parent object highlighted in the red rectangle in the hierarchy and the grass tiles instantiated in the scene. Remember, the game is not running, this happened in the editor.

Now we can go back to the OnSceneGui method of the MapEditor script.

The hot control id is taken as it will become usefull when we are placing the tiles. Because we are placing objects by clicking we don't want to select the just placed object in the inspector, otherwise we will loose the focus that is now on the object containing the MapEditor script. That means that every time we place a tile we will need to re select that object in order to place another tile because we have now selected the in the inspector the tile we have just placed. I know, confusing, try it yourself by commenting out lines 27, 35 and 46, see what happens.

On line 29 we raycast from the camera. I know that raycasting is usually done differently (Camera.main.ScreenToPointRay...), but when we are doing a raycast in the editor, that is how you proceed. It took me a while to find out and I was glad when I did.

Then I simply check that the ray we are casting is hitting the tiles (line 31). If that's the case and we are clicking (line 34), we set the boolean variable md (mouse down) to true. When that variable is true, the tile that is being hit by the raycast will change type (I will show that script next) according to the index of the tile chosen with the pop up field we saw earlier in the inspector. the reason why I used a boolean variable is that so I can keep the mouse button down and drag the cursor around in order to change the type of tile as I go, without having to keep clicking for each tile.

Last pieace of code, when the mouse is released, we let go of the hot control (line 45 to 48).

To confuse you even more, check the ChangeType method in the Tile script:

 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
public void ChangeType(int t)
 {
  type = t;

  switch (t) {
  case (int)Map.Tiles.WALL:

   AssignColorToMaterial (this.gameObject, grey);
   originalColor = grey;
   movementCost = Mathf.Infinity;

   break;

  case (int)Map.Tiles.GRASS:
   AssignColorToMaterial (this.gameObject, green);
   originalColor = green;
   movementCost = 1;
   break;

  case (int)Map.Tiles.SAND:
   AssignColorToMaterial (this.gameObject, sand);
   originalColor = sand;
   movementCost = 15;
   break;
  }
 }

This method will change the type of the tile (color and movement cost) according to the integer passed. If you don;t know about movement cost and why it's there, please read the previous post about path finding.

One important thing to notice is how we assign the new color to the material. You would be tempted to simply get the renderer reference and change the material color as you normally would in a script, but you cannot do that in the editor. This will cause a material leaking error.

If you want to achieve this, you will need to do a trick. That trick is the AssignColotToMaterial function, which is displayed below:



1
2
3
4
5
6
void AssignColorToMaterial(GameObject g,Color c)
 {
  var tempMaterial = new Material(g.GetComponent<Renderer>().sharedMaterial);
  tempMaterial.color = c;
  g.GetComponent<Renderer>().sharedMaterial = tempMaterial;
 }

We basically create a temporary material, change its color and assign it to the gameobject. This step is necessary in order to to what we want.

That's all folks.

This is all probably very confusing and I was struggling myself to understand what is going on, however, as it always is very much the case in coding, is all about trying it yourself and getting your hands dirty.

I hope this post will help you getting started in editor scripting and creating an awesome custom level editor.

Wednesday, 6 July 2016

Pathfinding for tile maps

Unity already comes with a pretty awesome feature which can be used for path finding and obstacle avoidance. I'm of course referring to the Nav Mesh and its other components.

However, I found that not very useful when it comes to 2D and tile map kind of games. It is of course possible to use it if you decide to utilize quads and planes, but I wanted to implement my own path finding system.

It turns out, it is not really hard, especially when there are algorithms out there that have been tested and used for years. For this project, I will show you how I wrote my "own version" of the Dijkstra algorithms. No, not the guy from The Witcher 3.

I will not post the whole project code as it is extensive and rather messy at this stage, however, I will put the main functions and classes needed.

First of all, we need a map, a simple grid of objects and our player of course.
In my experiment I created a small "level editor" by coding a custom editor so it would be easier to layout an awesome map.

And this is the awesome map itself:


Awesome indeed.

As you can see, I have 3 types of tiles: the "grass" tile, green color, the "sand" tile, yellow(ish) color and the "wall" tile, grey color.

The reason is to show how smart this algorithm can be. Every type of tile has a "cost": the grass tile costs 1 to move in to, the sand tile 15 and the wall is pretty much set to infinity.

When calculating the path you will see that the player (the little capsule on the bottom left corner) will attempt to avoid the sand when possible as it is "too expensive" to move in to. In simple words, it will try to find the least expensive path, which is not necessarily the shortest.

Here's a picture which illustrates this:


The player is trying to get to the tile in the red circle. It could very well cross the "sand field" by walking straight down south, instead, the calculated path would rather go around it. Each sand tile costs 15 action points (let's call them such) to move in to, and the player would have 5 sand tiles in front of him to reach the target tile, which makes a total of 75. By going around it as shown by the line, he would have to traverse 10 grass tiles, which cost 1 AP each, for a total of 10. So, 10 APs are much cheaper than 75.

The first class we need is the Node class:



public class Node  {

    public List<Node> tileNeighbors;
    public Map mapReference;

    public int x, y;

    public float distanceFromSource;
    public Node previousNode;

    public Node()
    {
        tileNeighbors = new List<Node>();
  //Debug.Log ("List initialized");
    }

    public float DistanceTo(Node n)
    {
        float d = 0;
        Vector3 current = mapReference.GetTilePositionAt(x, y);
        Vector3 to = mapReference.GetTilePositionAt(n.x, n.y);
        d = Vector2.Distance(current, to);

        return d;
    
    }


}

This class represents each tile on the map. The most important parameters in this class are: the list of nodes, which will contain all the neighbors tiles, the float distanceFromSource, which is the tile's physical distance form the source and a reference to the previous Node with the shortest path.

As part of the Dijkstra algorithm, we need to generate a so called "graph" with this Node class.
A graph is nothing but a two dimensional array of nodes.

  void GeneratePathGraph()
    {

        graph = new Node[mapWidth, mapHeight];

        //Populate neighbours list
        for (int x = 0; x < mapWidth; x++)
        {
            for (int y = 0; y < mapHeight; y++)
            {
                graph[x, y] = new Node();
                graph[x, y].mapReference = this;
                graph[x, y].x = x;
                graph[x, y].y = y;


            
            }
        }

  for (int x = 0; x < mapWidth; x++) {
   for (int y = 0; y < mapHeight; y++) {

    if (x > 0) {
     graph [x, y].tileNeighbors.Add (graph [x - 1, y]);

     //Diagonals
     /*
     if (y < mapHeight - 1) {
      graph [x, y].neighbours.Add (graph [x-1, y + 1]);
     }
     if (y > 0) {
      graph [x, y].neighbours.Add (graph [x-1, y - 1]);
     }*/
    }
    if (x < mapWidth - 1) {
     graph [x, y].tileNeighbors.Add (graph [x + 1, y]);

     //Diagonals
     /*
     if (y < mapHeight - 1) {
      graph [x, y].neighbours.Add (graph [x+1, y + 1]);
     }
     if (y > 0) {
      graph [x, y].neighbours.Add (graph [x+1, y - 1]);
     }*/
    }
    if (y > 0) {
     graph [x, y].tileNeighbors.Add (graph [x, y - 1]);
    }
    if (y < mapHeight - 1) {
     graph [x, y].tileNeighbors.Add (graph [x, y + 1]);
    }
   }
  }     
    
    }

With this function I generate this array and populate it with nodes. Also, through a second iteration, I populate the list of neighbors of each node with the neighbors tiles. As you can see, I commented out the diagonal tiles, and that is simply because I do not want diagonal movement. If you wish to have it, simply uncomment those lines.

Now, to the path generating function.


 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
   public  void GeneratePath()
    {

       
  
       List<Node> uncheckedNodes = new List<Node>();
       List<Node> currentPath = new List<Node>();

       Node sourceNode = graph[unitToMove.GetComponent<Unit>().currentTileX,
           unitToMove.GetComponent<Unit>().currentTileY];

       Node targetNode = graph[targetX,targetY];

    

  sourceNode.distanceFromSource = 0;
  sourceNode.previousNode = null;

 foreach (Node n in graph) {

   if (n != sourceNode) {    
    n.distanceFromSource = Mathf.Infinity;
    n.previousNode = null;
   }
   uncheckedNodes.Add (n);
  }

  while (uncheckedNodes.Count > 0) {   
 
   Node nodeWithMinDistance = GetNodeWithMinDistance (uncheckedNodes);

   if (nodeWithMinDistance == targetNode)
    break;
   
   uncheckedNodes.Remove (nodeWithMinDistance);

   foreach (Node n in nodeWithMinDistance.tileNeighbors) {
    float distance = nodeWithMinDistance.distanceFromSource + n.DistanceTo(nodeWithMinDistance)+ GetTileMovementCost (n.x, n.y);
   
    if (distance < n.distanceFromSource) {
     n.distanceFromSource = distance;
     n.previousNode = nodeWithMinDistance;
    }
   }
  
  } // Close while

  if (targetNode.previousNode == null) {
   Debug.Log ("No Path foud");
   line.SetVertexCount (0);
  }
  else {

   Node current = targetNode;
   while (current != null) {
    currentPath.Add (current);
    current = current.previousNode;
   }
 
   currentPath.Reverse ();
   unitToMove.GetComponent<Unit> ().currentPath = currentPath;

   DrawPath (currentPath);
  
  }


    }

Declare 2 lists of nodes, one for the unvisited nodes and the other one which will hold the generated path.

After that, create 2 node, the source node and the target node. The source node coordinates are taken from the Unit script, which is attached to the player. The script simply raycast downwards and detect the tile underneath and retrieves its coordinates, so it is constantly updated.

Similar thing for the target node, this time the mouse will update the coordinates, again, by raycast.

We then initialize the source node: its distance from the source is 0 (that node IS the source) and there's no previous node before it.

Next, we initialize every node in the our graph array: set their distance to infinity and the previous node reference to null. Also, add every node to the list of unvisited nodes.

On line 28 we start iterating inside this list. We create a temporary node object (nodeWithMinDistance ) and we set it to the node in the list with the least distance from the source. That's what the method GetNodeWithMinDistance(...) does, simply iterates inside the list and return the one with the minimum distance. In the first iteration, it should return the source node, as it has a distance of 0 and all the others have infinity.

This is the point where we check if we have reached our target node, in that case we break out of the while loop.

Also, very impostant, we remove the returned node from the list of unvisited nodes.

If not, we iterate inside the neighbor list of the returned node.

For each neighbr node we assign it a value to the  distanceFromSource parameter. This value, temporarily stored in the distance parameter, is calculated by adding the value of the same parameter of the current node (the one containing the neighbor list we are iterating in. In the first iteration of the while loop, is the source node), added to the physical distance between the tiles and also the movement cost.

Here is what's happening:

Let's assume that we are considering diagonals too. Starting from the source node on the bottom left, we have 3 neigbors tiles. The one above will have a distance from the source of 2. That is because the distance of the source node (which is 0) is added to the physical distance of the 2 tiles (which is 1 in this case as the tiles are nothing but 1x1 cubes) and its movement cost is added as well, which is 1 (because it's a grass tile). The total is 2.

For the diagonal tile, the distance is 2.4 because the physical distance between that tile and the source node is 1.4 (square root of 2 basically), plus its movement cost of course.

It is important to consider the physical distance for diagonal tiles for one reason: if diagonal tiles are considered at the same distance as adjacent tiles, this could happen:



Going frm tile A to tile B, the path generated has no reason to prefer adjacent tile to diagonal tiles, as they are mathematically at the same distance. So rather than going through a straight line, it might decide to act like in the picture above.

By calculating the physical distance of each tile, diagonals will have a value of distance from the source a little higher, which makes them a less favorable path to follow.

Continuing with our script, if the distance calculated is smaller than the current distance, that means that a shorter path has been found and the distanceFromSource parameter is updated.

This process will continue for each node until we reach the target node.

When we do, the program will exit the while loop.

At this point, if the previousNode of the target node is null means that no path was found, so the while loop iterated through the whole list of nodes without finding a route.

If not, we simply populate the currentPath list by grabbing the previousNode node in each previousNode reference of each node starting from the target node. This is a linked list technique, you can find plenty of tutorials on it online.

At this point the currentPath list contains all the nodes, from target to source. After reversing it, we can assign it to the player (called unitToMove) so it has a path to follow and we can draw the path using line renderers.

It is important to kow that with this system, the player will still be able to travers WALL tiles if no other path is found. That is because the value assigned is not (obviously) infinity, so it can be calculated. To avoid that we can simply detect if the path goes through tiles of type wall and break it when it happens.

Nonetheless, this is one of the ways we can implement path finding for tile based games.

Example scene here.


Tuesday, 21 June 2016

Using "ghosts" to create a "wrapped" world

Ok the title of this post could be a little misleading.

What I want to show you with this small project is how we can create a wrapping effect for our player in a 2D environment. And what I mean by that is I'm trying to achieve the "Pac-Man" effect or the "Asteroid" effect: the player exits the screen from one end, reappears from the other one.

These are the assets used: tiles and the racoon.

Here is a screenshot of the effect I'm talking about:


As you can see by my beautiful arrows, the character is leaving the screen to the left and coming back in the screen from the right side.

To achieve this effect we use ghosts.

What are ghosts you say? Well they are nothing more than copies of the player object which move in relation to it outside of the visible screen.

If we look at the scene, this is what is actually happening:



The "real" player character is the one in the red circle, the other ones are just copies of it.

For this particular project I used only 3 ghosts, you can have up to 8 if you want the effect to work for all directions. I didn't want, for example, the character to pop out from the bottom whenever I jumped from the very top platform. That was a choice I made, which is not necessarily what you might want for your game.

We can achieve this with one simple script:


 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
public class Ghosts : MonoBehaviour {

 float screenWidth;
 float screenHeight;

 Vector3 topLeft;
 Vector3 bottomRight;

 GameObject[] ghosts;
 Vector3[] ghostPosition;

 // Use this for initialization
 void Start () {

  topLeft = Camera.main.ViewportToWorldPoint(new Vector3(0,1,transform.position.z));
  bottomRight = Camera.main.ViewportToWorldPoint(new Vector3(1,0,transform.position.z));

  screenWidth = bottomRight.x - topLeft.x;
  screenHeight = topLeft.y - bottomRight.y;

  ghosts = new GameObject[3];
  ghostPosition = new Vector3[3];

  ghostPosition [0] = new Vector3 (screenWidth, 0, 0);
  ghosts[0] = Instantiate (this.gameObject, transform.position + ghostPosition[0], this.gameObject.transform.rotation)as GameObject;

  ghostPosition [1] =  new Vector3 (-screenWidth, 0, 0);
  ghosts[1] = Instantiate (this.gameObject, transform.position + ghostPosition[1], this.gameObject.transform.rotation)as GameObject;

  ghostPosition [2] =  new Vector3 (0, screenHeight, 0);
  ghosts[2] = Instantiate (this.gameObject, transform.position + ghostPosition[2], this.gameObject.transform.rotation)as GameObject;

 foreach (GameObject g in ghosts) {
   DestroyImmediate (g.GetComponent<Ghosts> ());
   DestroyImmediate (g.GetComponent<Rigidbody2D> ());
   DestroyImmediate (g.GetComponent<BoxCollider2D> ());
   DestroyImmediate (g.GetComponent<Movement> ());
  }
 
 
 }

 // Update is called once per frame
 void Update () {

  CheckGhostsPosition ();
  PlaceGhosts ();
 
 }

 void CheckGhostsPosition()
 {
  foreach (GameObject g in ghosts) {
   if (g.transform.position.x < bottomRight.x &&  g.transform.position.x > topLeft.x &&
    g.transform.position.y > bottomRight.y && g.transform.position.y < topLeft.y)
    this.gameObject.transform.position = g.transform.position;
  }
 }
 void PlaceGhosts()
 {
  int i = 0;
  foreach (GameObject g in ghosts) {
   g.transform.position = transform.position + ghostPosition [i];
   g.transform.rotation = transform.rotation;
   g.transform.localScale = transform.localScale;
   i++;
  }

 }
}

The character gameobject also has 2 other scripts attached, one for the movement and one for the animation. I have separated movement and animation for a reason which I will explain shortly.

To begin with, we need to get the screen width and height in world space: this is what happens from line 15 to 19. I get the bottom right and top left corner position of the screen in world space coordinates and I calculate the width and the height of the viewport.

This is done because the ghosts, for example, the 2 side ones will be placed a screen width distance away from the main character.

From line 24 to 31 I instantiate the 3 ghosts, store them in an array and place them accordingly. I also store their position in a Vector3 array so it makes it easier to iterate their position later in the script.

The foreach loop on line 33 is used to eliminate all unnecessary components from the ghosts I just instantiated. First of all, the Ghosts script that we are writing right now: we don't want the new instances to create new ones themselves or this will result in a infinite amount of ghosts!

I eliminate the Rigidbody2D  and the CircleCollider2D as I don't want the ghosts to bump into things while off screen. Also, they don't need the Movement script, as they will be placed around the scene from this script. The only component they need is the CharacterAnimation script, which simply handles their animation just like the main character.

The CheckGhostsPosition() method is called every frame and it checks for the position of every ghost. If one of them happens to be within the screen, the main character will be immediately "teleported" to that position so that the ghosts will be again placed outside the visible screen.

Finally the PlaceGhosts() simply iterate through all the ghosts and place them according to the main character position.

I will post the other 2 script, CharacterAnimation and Movement, however, I will not go through them
because, well....they are so simple.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class CharacterAnimation : MonoBehaviour {

 Animator anim;

 // Use this for initialization
 void Start () {

  anim = GetComponent<Animator> ();
 
 }
 
 // Update is called once per frame
 void Update () {

  float x = Input.GetAxis ("Horizontal");
  anim.SetFloat ("Speed", Mathf.Abs(x));


 }
}



 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
public class Movement : MonoBehaviour {

 public float runSpeed = 5;
 public float jumpForce = 50;


 Rigidbody2D rb2d;
 CircleCollider2D cc2d;



 bool isFacingRight = true;
 public bool grounded;

 // Use this for initialization
 void Start () {

  rb2d = GetComponent<Rigidbody2D> ();
  cc2d = GetComponent<CircleCollider2D> ();
 
 }
 
 // Update is called once per frame
 void Update () {

  float x = Input.GetAxis ("Horizontal");

  MoveChar (x);    

  if (Input.GetKeyDown (KeyCode.Space) && grounded) {
   rb2d.AddForce (new Vector2 (0,jumpForce),ForceMode2D.Impulse);
   grounded = false;
  }
 }

 void MoveChar(float x)
 {
  Vector3 nextPos = new Vector3 ( x * runSpeed * Time.deltaTime, 0,0);

  transform.position = transform.position + nextPos;

  if (x > 0 && !isFacingRight || x < 0 && isFacingRight)
   Flip ();

 }

 void Flip()
 {
  transform.localScale = new Vector3 (transform.localScale.x * -1, transform.localScale.y, transform.localScale.z);
  isFacingRight = !isFacingRight;
 }

 void OnCollisionEnter2D(Collision2D c)
 {
  if (c.collider.tag.Equals ("Ground"))
   grounded = true;

 }




}


An example scene is playable here.