Saturday, March 25, 2017

Movement script for Unity

First of all let our character move left and right. We will make it funny, our character will go left when we have one finger on the screen, and will go right if this finger in moving on the screen.

To do so create a C# script and in our "Update" function write:

if (Input.GetTouch(0).phase == TouchPhase.Stationary)
        {
            transform.Translate(1 * Time.deltaTime, 0, 0);
        }


This code means that every frame (in Update function) the game will check if you have at least one finger on the screen (the first one, that touched the screen counts) and if that finger isn't moving (TouchPhase.Stationary). If it is so our object (that we will attach our script later) will go 1*Time.deltaTime in x axe. Here we are using Time.deltaTime because it allows us to get the same movement speed if we have 30 FPS, 60 FPS and any other*.

Now write:

if (Input.GetTouch(0).phase == TouchPhase.Moved)
        {
            transform.Translate(-1 * Time.deltaTime, 0, 0);
        }


 It is same as above but instead of 1 we have -1 to get the movement in opposite direction.

Now the only thing to do is to drag our script from "Assets" window in Unity and drop it on our object. To be sure if our script is attached click the object and open ""Inspector" window.

As you can see i have attached "New Behavior Script 1" script to my object.





*because Time.deltaTime is called every frame and Time.deltaTime is the duration of our frame.That allows us to have constant movement speed since frames per second times duration of a frame is always the same.

1 comment:

  1. Great to see, that Unity isn't such monster, unlike Unreal for you ;p

    Kind regards,
    Artur "ekhart" Dębkowski
    http://ekhart.pl

    ReplyDelete