25
2/2/2015 Parallax scrolling — Pixelnest Studio http://pixelnest.io/tutorials/2dgameunity/parallaxscrolling/ 1/25 Our game — Steredenn — is on Steam Greenlight. Help us with your vote! Back to Pixelnest Tutorial: Creating a 2D game with Unity follow us on twitter Prev. Summary Next A whole new way to plan your team's time. Powered by Fusion Parallax scrolling Pixelnest 18 nov. 2013 For the moment, we have created a static scene with a player and some enemies. It's a bit boring. Time to enhance our background and scene. An effect that you find in every single 2D game for 15 years is

Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 1/25

Our game — Steredenn — is on Steam Greenlight. Help us with your vote!

Back to Pixelnest Tutorial: Creating a 2D game withUnity

follow us on twitter

← Prev. Summary Next →

A whole new way to plan your team's time.Powered by Fusion

Parallax scrolling

Pixelnest

18 nov. 2013

For the moment, we have created a static scene with a playerand some enemies. It's a bit boring. Time to enhance ourbackground and scene.

An effect that you find in every single 2D game for 15 years is

Page 2: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 2/25

"parallax scrolling".

To make it short, the idea is to move the background layers atdifferent speeds (i.e., the farther the layer is, the slower itmoves). If done correctly, this gives an illusion of depth. It's acool, nice and easy­to­do effect.

Moreover, many shmups use a scrolling in one — or more —axis (except the original one, Space Invaders).

Let's implement that in Unity.

Theory: defining the scrolling in ourgame

Adding a scrolling axis need a bit of thinking on how we willmake the game with this new aspect.

It's good to think before coding. :)

What do we want to move?

We have a decision to take here :

1. First choice: The player and the camera move. The rest isfixed.

2. Second choice: The player and the camera are static. Thelevel is a treadmill.

Page 3: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 3/25

The first choice is a no­brainer if you have a Perspectivecamera. The parallax is obvious: background elements have ahigher depth. Thus, they are behind and seems to moveslower.

But in a standard 2D game in Unity, we use an Orthographiccamera. We don't have depth at render.

About the camera : Remember the "Projection" property of your cameragame object. It's set to Orthographic in our game. Perspective means that the camera is a classic 3D camera, with depthmanagement. Orthographic is a camera that renders everything at the samedepth. It's particularly useful for a GUI or a 2D game.

In order to add the parallax scrolling effect to our game, thesolution is to mix both choices. We will have two scrollings:

The player is moving forward along with the camera.Background elements are moving at different speeds (inaddition to the camera movement).

Note : You may ask: "Why don't we just set the camera as a child of theplayer object?". Indeed, in Unity, if you set an object (camera or not) as asub­child of a game object, this object will maintain its relative position toits parent. So if the camera is a child of the player and is centered on him, itwill stay that way and will follow him exactly. It could be a solution, but thiswould not fit with our gameplay.

In a shmup, the camera restricts the player movement. If the camera movesalong with the player for both horizontal and vertical axis, then the player is

Page 4: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 4/25

free to go where he wants. We DO want to keep the player inside a restrictedarea.

We would also recommend to always keep the camera independent in a 2Dgame. Even in a platformer, the camera isn't strictly linked to the player: itfollows him under some restrictions. Super Mario World has probably onethe best camera possible for a platformer. You may have a look at how it isdone.

Spawning enemies

Adding a scrolling to our game has consequences, especiallyconcerning enemies. Currently, they are just moving andshooting as soon as the game starts. However, we want themto wait and be invincible until they spawn.

How do we spawn enemies? It depends on the game,definitely. You could define events that spawn enemies whenthey are triggered, spawn points, pre­determined positions,etc.

Here is what we will do: We position the Poulpies on thescene directly (by dragging the Prefab onto the scene). Bydefault, they are static and invincibles until the camerareaches and activates them.

Page 5: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 5/25

The nice idea here is that you can use the Unity editor to setthe enemies. You read right: without doing anything, youalready have a level editor.

Once again, it's a choice, not science. ;)

Note : We truly think that using the Unity editor as a level editor is valuable,unless you have time, money and dedicated level designers that need specialtools.

Planes

First, we must define what our planes are and for each, if it'sa loop or not. A looping background will repeat over and overagain during the level execution. E.g., it's particularly usefulfor things like the sky.

Add a new layer to the scene for the background elements.

We are going to have:

Page 6: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 6/25

Layer Loop Position

Background with the sky Yes (0, 0, 10)

Background (1st row of flying platforms) No (0, 0, 9)

Middleground (2nd row of flyingplatforms) No (0, 0, 5)

Foreground with players and enemies No (0, 0, 0)

We could imagine to have some layers before the player too.Just keep the Z positions between [0, 10] , otherwise you willneed to tweak the camera.

Careful with that axe, Eugene : If you add layers ahead of the foregroundlayer, be careful with the visibility. Many games do not use this techniquebecause it reduces the clearness of the game.

Page 7: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 7/25

Practice: Diving into the code

Okay, we saw how implementing a parallax scrolling affectsour game.

Did you know? "Scrolling shooters" is another name used for the shmups.

But enough thoughts, time to practice!

Unity has some parallax scrolling scripts in its standardpackages (take a look at the 2D platformer demo on the AssetStore). You can of course use them, but we found it would beinteresting to build one from scratch the first time.

Standard packages : These are practicals, but be careful to not abuse ofthem. Using standard packages can block your thoughts and will not makeyour game stand out of the crowd. They give a Unity feel to your gameplay. Remember all the flash game clones?

Simple scrolling

We will start with the easy part: scrolling backgroundswithout looping.

Remember the "MoveScript" we used before? The basis is thesame: a speed and a direction applied over time.

Create a new "ScrollingScript" script:

Page 8: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 8/25

using UnityEngine;

/// <summary>/// Parallax scrolling script that should be assigned to a layer/// </summary>public class ScrollingScript : MonoBehaviour /// <summary> /// Scrolling speed /// </summary> public Vector2 speed = new Vector2(2, 2);

/// <summary> /// Moving direction /// </summary> public Vector2 direction = new Vector2(‐1, 0);

/// <summary> /// Movement should be applied to camera /// </summary> public bool isLinkedToCamera = false;

void Update() // Movement Vector3 movement = new Vector3( speed.x * direction.x, speed.y * direction.y, 0);

movement *= Time.deltaTime; transform.Translate(movement);

// Move the camera if (isLinkedToCamera) Camera.main.transform.Translate(movement);

Page 9: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 9/25

Attach the script to these game objects with these values:

Layer Speed DirectionLinked to Camera

0 ­ Background (1, 1) (‐1, 0, 0) No1 ­ Background

elements(1.5,

1.5)(‐1, 0, 0) No

2 ­ Middleground (2.5,

2.5)(‐1, 0, 0) No

3 ­ Foreground (1, 1) (1, 0, 0) Yes

For a convincing result, add elements to the scene:

Add a third background part after the two previous ones.Add some small platforms in the layer 1 ‐ Backgroundelements .Add platforms in the layer 2 ‐ Middleground .Add enemies on the right of the layer 3 ‐ Foreground , farfrom the camera.

The result:

Page 10: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 10/25

Not bad! But we can see that enemies move and shoot whenthey are out of the camera, even before they spawn!

Moreover, they are never recycled when they pass the player(zoom out in the "Scene" view, and look at the left of thescene: the Poulpies are still moving).

Note : Experiment with the values. :)

We'll fix these problems later. First, we need to manage theinfinite background (the sky).

Infinite background scrolling

In order to get an infinite background, we only need to watch

Page 11: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 11/25

the child which is at the left of the infinite layer.

When this object goes beyond the camera left edge, we moveit to the right of the layer. Indefinitely.

For a layer filled with images, notice that you need aminimum size to cover the camera field, so we never seewhat's behind. Here it's 3 parts for the sky, but it's completelyarbitrary.

Find the correct balance between resource consumption andflexibility for your game.

In our case, the idea is that we will get all the children on thelayer and check their renderer.

A note about using the renderer component : This method won't work withinvisible objects (e.g., the ones handling scripts). However, a use case whenyou need to do this on invisible objects is unlikely.

Page 12: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 12/25

We will use an handy method to check whether an object'srenderer is visible by the camera. We've found it on thecommunity wiki. It's neither a class nor a script, but a C#class extension.

Extension : The C# language allows you to extend a class with extensions,without needing the base source code of the class. Create a static method starting with a first parameter which looks like this:this Type currentInstance . The Type class will now have a new method availableeverywhere your own class is available. Inside the extension method, you can refer to the current instance calling themethod by using the currentInstance parameter instead of this .

The "RendererExtensions" script

Create a new C# file named "RendererExtensions.cs" and fillit with:

using UnityEngine;

public static class RendererExtensions public static bool IsVisibleFrom(this Renderer renderer, Camera camera) Plane[] planes = GeometryUtility.CalculateFrustumPlanes(camera); return GeometryUtility.TestPlanesAABB(planes, renderer.bounds);

Simple, isn't it?

Page 13: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 13/25

Namespaces : You might have already noted that Unity doesn't add anamespace around a MonoBehaviour script when you create it from the "Project"view. And yet Unity does handle namespaces... Except when you use adefault value on a method parameter. And it sucks.

In this tutorial, we are not using namespaces at all. However, in your realproject, you might consider to use them. If not, prefix your classes andbehaviours to avoid a collision with a third­party library (like NGUI).

We will call this method on the leftmost object of the infinitelayer.

Full "ScrollingScript"

Observe the full "ScrollingScript" (explanations below):

using System.Collections.Generic;using System.Linq;using UnityEngine;

/// <summary>/// Parallax scrolling script that should be assigned to a layer/// </summary>public class ScrollingScript : MonoBehaviour /// <summary> /// Scrolling speed /// </summary> public Vector2 speed = new Vector2(10, 10);

/// <summary> /// Moving direction /// </summary> public Vector2 direction = new Vector2(‐1, 0);

Page 14: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 14/25

/// <summary> /// Movement should be applied to camera /// </summary> public bool isLinkedToCamera = false;

/// <summary> /// 1 ‐ Background is infinite /// </summary> public bool isLooping = false;

/// <summary> /// 2 ‐ List of children with a renderer. /// </summary> private List<Transform> backgroundPart;

// 3 ‐ Get all the children void Start() // For infinite background only if (isLooping) // Get all the children of the layer with a renderer backgroundPart = new List<Transform>();

for (int i = 0; i < transform.childCount; i++) Transform child = transform.GetChild(i);

// Add only the visible children if (child.renderer != null) backgroundPart.Add(child);

// Sort by position. // Note: Get the children from left to right. // We would need to add a few conditions to handle

Page 15: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 15/25

// all the possible scrolling directions. backgroundPart = backgroundPart.OrderBy( t => t.position.x ).ToList();

void Update() // Movement Vector3 movement = new Vector3( speed.x * direction.x, speed.y * direction.y, 0);

movement *= Time.deltaTime; transform.Translate(movement);

// Move the camera if (isLinkedToCamera) Camera.main.transform.Translate(movement);

// 4 ‐ Loop if (isLooping) // Get the first object. // The list is ordered from left (x position) to right. Transform firstChild = backgroundPart.FirstOrDefault();

if (firstChild != null) // Check if the child is already (partly) before the camera. // We test the position first because the IsVisibleFrom // method is a bit heavier to execute. if (firstChild.position.x < Camera.main.transform.position.x) // If the child is already on the left of the camera,

Page 16: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 16/25

// we test if it's completely outside and needs to be // recycled. if (firstChild.renderer.IsVisibleFrom(Camera.main) == false) // Get the last child position. Transform lastChild = backgroundPart.LastOrDefault(); Vector3 lastPosition = lastChild.transform.position; Vector3 lastSize = (lastChild.renderer.bounds.max ‐ lastChild.renderer.bounds.min);

// Set the position of the recyled one to be AFTER // the last child. // Note: Only work for horizontal scrolling currently. firstChild.position = new Vector3(lastPosition.x + lastSize.x, firstChild.position.y, firstChild.position.z);

// Set the recycled child to the last position // of the backgroundPart list. backgroundPart.Remove(firstChild); backgroundPart.Add(firstChild);

(The numbers in the comments refer to the explanationsbelow)

Explanations

1. We need a public variable to turn on the "looping" modein the "Inspector" view.

2. We also have to use a private variable to store the layer

Page 17: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 17/25

children.3. In the Start() method, we set the backgroundPart list with the

children that have a renderer. Thanks to a bit of LINQ, weorder them by their X position and put the leftmost at thefirst position of the array.

4. In the Update() method, if the isLooping flag is set to true ,we retrieve the first child stored in the backgroundPart list.We test if it's completely outside the camera field. Whenit's the case, we change its position to be after the last(rightmost) child. Finally, we put it at the last position ofbackgroundPart list.

Indeed, the backgroundPart is the exact representation of what ishappening in the scene.

Remember to enable the "Is Looping" property of the"ScrollingScript" for the 0 ‐ Background in the "Inspector" pane.Otherwise, it will (predictably enough) not work.

(Click on the image to see the animation)

Yes! We finally have a functional "parallax scrolling"

Page 18: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 18/25

implementation.

Note: Why don't we use the OnBecameVisible() and OnBecameInvisible() methods?Because they are broken.

The basic idea of these methods is to execute a fragment of code when theobject is rendered (or vice­versa). They work like the Start() or Stop()methods (if you need one, simply add the method in the MonoBehaviour andUnity will use it).

The problem is that these methods are also called when rendered by the"Scene" view of the Unity editor. This means that we will not get the samebehavior in the Unity editor and in a build (whatever the platform is). This isdangerous and absurd. We highly recommend to avoid these methods.

Bonus: Enhancing existing scripts

Let's update our previous scripts.

Enemy v2 with spawn

We said earlier that enemies should be disabled until they arevisible by the camera.

They should also be removed once they are completely off thescreen.

We need to update "EnemyScript", so it will:

1. Disable the movement, the collider and the auto­fire

Page 19: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 19/25

(when initialized).2. Check when the renderer is inside the camera sight.3. Activate itself.4. Destroy the game object when it's outside the camera.

(The numbers refer to the comments in the code)

using UnityEngine;

/// <summary>/// Enemy generic behavior/// </summary>public class EnemyScript : MonoBehaviour private bool hasSpawn; private MoveScript moveScript; private WeaponScript[] weapons;

void Awake() // Retrieve the weapon only once weapons = GetComponentsInChildren<WeaponScript>();

// Retrieve scripts to disable when not spawn moveScript = GetComponent<MoveScript>();

// 1 ‐ Disable everything void Start() hasSpawn = false;

// Disable everything // ‐‐ collider collider2D.enabled = false; // ‐‐ Moving

Page 20: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 20/25

moveScript.enabled = false; // ‐‐ Shooting foreach (WeaponScript weapon in weapons) weapon.enabled = false;

void Update() // 2 ‐ Check if the enemy has spawned. if (hasSpawn == false) if (renderer.IsVisibleFrom(Camera.main)) Spawn(); else // Auto‐fire foreach (WeaponScript weapon in weapons) if (weapon != null && weapon.enabled && weapon.CanAttack) weapon.Attack(true);

// 4 ‐ Out of the camera ? Destroy the game object. if (renderer.IsVisibleFrom(Camera.main) == false) Destroy(gameObject);

// 3 ‐ Activate itself. private void Spawn()

Page 21: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 21/25

hasSpawn = true;

// Enable everything // ‐‐ Collider collider2D.enabled = true; // ‐‐ Moving moveScript.enabled = true; // ‐‐ Shooting foreach (WeaponScript weapon in weapons) weapon.enabled = true;

Start the game. Yes, there's a bug.

Disabling the "MoveScript" as a negative effect: The playernever reaches the enemies as they're all moving with the 3 ‐Foreground layer scrolling:

Remember: we've added a "ScrollingScript" to this layer in

Page 22: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 22/25

order to move the camera along with the player.

But there is a simple solution: move the "ScrollingScript"from the 3 ‐ Foreground layer to the player!

Why not after all? The only thing that is moving in this layeris him, and the script is not specific to a kind of object.

Push the "Play" button and observe: It works.

1. Enemies are disabled until they spawn (i.e., until thecamera reaches their positions).

2. Then they disappear when they are outside the camera.

(Click on the image to see what happens)

Keeping the player in the camera bounds

You might have noticed that the player is not (yet) restrictedto the camera area. "Play" the game, push the "Left Arrow"and watch him leaves the camera.

Page 23: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 23/25

We have to fix that.

Open the "PlayerScript", and add this at the end of the"Update()" method:

void Update() // ...

// 6 ‐ Make sure we are not outside the camera bounds var dist = (transform.position ‐ Camera.main.transform.position).z;

var leftBorder = Camera.main.ViewportToWorldPoint( new Vector3(0, 0, dist) ).x;

var rightBorder = Camera.main.ViewportToWorldPoint( new Vector3(1, 0, dist) ).x;

var topBorder = Camera.main.ViewportToWorldPoint( new Vector3(0, 0, dist) ).y;

var bottomBorder = Camera.main.ViewportToWorldPoint( new Vector3(0, 1, dist) ).y;

transform.position = new Vector3( Mathf.Clamp(transform.position.x, leftBorder, rightBorder), Mathf.Clamp(transform.position.y, topBorder, bottomBorder), transform.position.z );

// End of the update method

Page 24: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 24/25

Nothing complicated, just verbose.

We get the camera edges and we make sure the playerposition (the center of the sprite) is inside the area borders.

Tweak the code to better understand what is happening.

Next step

We have a scrolling shooter!

We have just learned how to add a scrolling mechanism toour game, as well as a parallax effect for the backgroundlayers. However, the current code only works for right to leftscrolling. But with your new knowledge, you should be able toenhance it and make it work for all scrolling directions(bonus: We did it as someone was stuck on the subject, clickto see the code and an animation).

Still, the game really needs some tweaks to be playable. Forexample:

Reducing the sprite sizes.Adjusting the speeds.Adding more enemies.Making it fun.

We will address these points in our upcoming chapter about

Page 25: Parallax scrollingmentorshipacademy.org/ourpages/auto/2014/8/24... · 8/24/2014  · But in a standard 2D game in Unity, we use an ... (like NGUI). We will call this method on the

2/2/2015 Parallax scrolling — Pixelnest Studio

http://pixelnest.io/tutorials/2d­game­unity/parallax­scrolling/ 25/25

click to get more information about our upcoming game!

gameplay tweaking (not released yet, unfortunately). For themoment, you can experiment. ;)

In the next chapter, we will focus our attention on how tomake the game a bit more... flashy. With particles!

← Prev. Summary Next →

© 2013 pixelnest.io ­ we craft games and apps