Time for action – declare a variable to store the Screen midpoint

  1. Modify your Script so that it looks like this (you can get rid of the Debug.Log() function call):
      function Update () {
        var halfW : float = Screen.width/2;
        transform.position.x = (Input.mousePosition.x -halfW)/halfW;
      }

That code looks a lot cleaner. Not only is it easier to read, but we've knocked out some of those confusing brackets in the second line.

What just happened – we've gone too var

We've used the special var keyword to declare our variable (bucket). I chose the name halfW, which is short for "half width"—half the width of the screen. You can choose any name you like for a variable as long as it isn't a reserved Unity keyword, and it doesn't break any of the naming rules ...

Get Unity 4.x Game Development by Example Beginner's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.