Unity scripts etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
Unity scripts etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

Using Joystick Step by Step with Unity

Unity and Joystick Control

 Hello,

In this article, I will tell you how to control the game with Joystick with Unity. Users prefer to play their games on mobile devices as well as computers and consoles and similar platforms, and writing games that will work on mobile is very popular today. We can use the advantage of the touch screen by adding a joystick to our game screen and make our game preferable.

So how to add Joystick to unity game project? How to control the joystick? How to move a character or object using a joystick? I will explain all of them step by step in my article.

I will start by assuming that you have already created a Unity project and added a character or an object that you want to move with a plane and a joystick to the game scene.

Adding Joystick

Step 1 : Add Collider and Rigidbody to the character we created.

Step 2 : Let’s add the Joystick package offered for free to our project from the link below.

Step 3: After downloading and importing our package using Package Manager, let’s add a Canvas to our project. It doesn’t matter if our project is 2D or 3D, it works in both cases. Because we need a Canvas object to place the joystick on the screen.

Step 4: Then drag and drop the Fixed Joystick from the prefabs folder in the package folders under the Canvas we created in the previous step. Since we have selected the prefab whose position is Fixed by default, the joystick will be placed in the lower left corner of the screen.

Step 5: Since we prefer to use our game on the mobile platform and with the screen tilted, let’s open the Build Settings screen, after adding the scene to the build screen, select IOS or Android and click Switch Platform.

On the Main Screen, where the Scene and Game windows are, Smilator should now be displayed instead of Game.

Step 6: In this step, let’s move on to screen sizing. Let’s change the Scaler property in the Inspector section of the Canvas we added to Scale With Screen Size. Here we can enter the screen sizes we are targeting.

Joystick Control

Step 7: After adjusting the screen sizes, it’s time for the coding part that will allow us to move our character or object. We can add the following codes to the Script file we will create in our Script folder.

 [SerializeField] private FixedJoystick _joystick;
[SerializeField] private float _moveSpeed;

private void FixedUpdate()
{
JoystickMovement();
}

void JoystickMovement()
{
float horizontal = _joystick.Horizontal;
float vertical = _joystick.Vertical;
Vector3 addedPosition = new Vector3(horizontal * _moveSpeed * Time.deltaTime, 0, vertical * _moveSpeed * Time.deltaTime);
transform.position += addedPosition;
}
Object Control with Joystick

I added a flat floor and a capsule as above for an example. We can think of it as a character. I especially tilted the capsule sideways by playing with its rotation because it already has a rigid body, so it automatically falls to the side as soon as we start the game.

Step 8: Let’s add the Script we wrote above to our character. Let’s not forget to assign our joystick that we added from the package folders to the _joystick variable, which we define as private here but make it accessible with the SerialiseField expression.

I tried to explain step by step how to add a joystick to a game in Unity and how to control it, I hope it was useful.

Thanks for your reading.

Selin.


Unity ile Adım Adım Joystick Kullanımı

Unity ve Joystick Kontrolü

 Merhaba,

Bu yazımda sizlere Unity ile oyunu Joystick ile kontrol etme nasıl yapılır bunu anlatacağım. Kullanıcılar oyunlarını bilgisayar ve konsol ve benzeri platformların yanında mobil cihazlarda da oynamayı çokça tercih ediyorlar ve mobilde çalışacak oyun yazabilmek günümüzde oldukça revaçta. Dokunmatik ekranın avantajını oyun ekranımıza joystick ekleyerek kullanabilir ve oyunumuzun tercih edilir olmasını sağlayabiliriz.

Peki unity oyun projesine Joystick nasıl eklenir? Joystick kontrolü nasıl yapılır? Joystick kullanarak karakter ya da nesne nasıl hareket ettirilir? Hepsini yazımda adım adım anlatacağım.

Halihazırda bir Unity projesi oluşturduğunuzu, bir zemin(plane) ve joystick ile hareket etmesini istediğiniz bir karakter veya bir nesneyi oyun sahnesine eklediğinizi varsayarak anlatmaya başlıyorum.

Joystick Ekleme

1 . Adım : Oluşturduğumuz karaktere Collider ve Rigidbody ekleyelim.

2 . Adım : Ücretsiz bir şekilde sunulan Joystick paketini aşağıdaki linkten projemize ekleyelim.

3 . Adım: Package Manager kullanarak paketimizi sırasıyla download ve import ettikten sonra projemize bir Canvas ekleyelim. Projemizin 2D veya 3D olması önemli değil, her iki durumda da çalışır. Çünkü Joystick’i ekrana yerleştirmek için bir Canvas nesnesine ihtiyacımız var.

4 . Adım: Daha sonra paket klasörleri içerisindeki prefabs klasöründen Fixed Joystick’i bir önceki adımda oluşturduğumuz Canvas’ın altına sürükleyerek bırakalım. Pozisyonu default olarak Fixed belirlenen prefab’ı seçtiğimiz için joystick ekranın sol alt köşesine yerleşecek.

5. Adım: Oyunumuzu mobil platformda ve ekran yana yatıkken kullanmayı tercih ettiğimiz için Build Settings ekranını açalım, Sahneyi build ekranına ekledikten sonra IOS veya Android’i seçerek Switch Platform’a tıklayalım.

Ana Ekranda Scene ve Game pencerelerinin olduğu kısımda artık Game yerine Smilator görüntüleniyor olması gerekir.

6 . Adım: Bu adımda ekran boyutlamasına geçelim. Eklediğimiz Canvas’ın Inspector kısmındaki Scaler özelliğini Scale With Screen Size olarak değiştirelim. Burada hedeflediğimiz ekran boyutlarını girebiliriz.

Joystick Kontrolü

7 . Adım: Ekran boyutlarını da ayarladıktan sonra sıra karakterimizi veya nesnemizi hareket ettirmemizi sağlayacak kodlama kısmına geldi. Script klasörümüz içerisine oluşturacağımız Script dosyasına aşağıdaki kodları ekleyebiliriz.


[SerializeField] private FixedJoystick _joystick;
[SerializeField] private float _moveSpeed;

private void FixedUpdate()
{
JoystickMovement();
}

void JoystickMovement()
{
float horizontal = _joystick.Horizontal;
float vertical = _joystick.Vertical;
Vector3 addedPosition = new Vector3(horizontal * _moveSpeed * Time.deltaTime, 0, vertical * _moveSpeed * Time.deltaTime);
transform.position += addedPosition;
}
Joystick ile Nesne Kontrolü

Ben örnek olması için yukarıdaki gibi düz bir zemin ve bir kapsül ekledim. Bunu karakter gibi düşünebiliriz. Kapsülü rotation’ı ile oynayarak özellikle yan yatırdım çünkü rigidbody’si bulunduğundan zaten oyunu başlattığımız an kendiliğinden yana düşüyor.

8 . Adım: Yukarıda yazmış olduğumuz Script’i karakterimize ekleyelim. Burada private olarak tanımladığımız ancak SerializeField ifadesiyle erişilebilir olmasını sağladığımız _joystick değişkenine paket klasörlerinden eklediğimiz joystick’imizi atamayı unutmayalım.

Unity’de bir oyuna Joystick nasıl eklenir ve nasıl kontrol edilir bunu adım adım anlatmaya çalıştım, umarım faydalı olmuştur.

Teşekkürler.

Selin.


Script Basics in Unity

 


I met Unity about 5 months ago thanks to a Game Academy. Before that, I had no purpose and interest in writing games.

Thanks to the academy I was accepted by chance, I started to work on games and to tell a lie, I liked it. Since I have a C# foundation, I started the subject with some self-confidence, but I learned with bitter experience that what I know in software is a camel’s ear compared to what I don’t know, because this C# was not the C# I knew 😛

Fortunately, I adapted quickly and developed small game projects as the academy progressed. At the end of the 3-month period, I submitted my graduation project. If I get accepted and graduate from the programme, I will announce it here.

Let’s talk about Unity.

What is Unity?

We can define Unity as a game engine that facilitates and accelerates the game development process. Thanks to the toolkits it contains, we can design 2D and 3D games.

It has a very large community and even its own training page called UnityLearn if we know English, and I think it is very useful and comprehensive for learning simple developments.

Using Unity, we can develop games to be played on different platforms such as computers, mobile devices and game consoles.

There is an Asset Store where ready-made assets, models, sounds can be downloaded with paid and free options. From here, we can download assets such as simple objects or characters and use them directly in our project.

Scripting

Let’s come to Scripting, which is the main subject of my article. In Unity, we can move game objects, add interactions, create game mechanics and many other things with the scripts we write, that is, with code files.

It is ideal to create a folder named Scripts under the project folders and collect all the Script files we will write in this folder. We can do this by right clicking on the project folders with the Create Folder option.

In the screenshot above we can see the folders of a game I developed. I have downloaded two different asset folders from AssetStore and these are also visible among the project folders. The Script folder I created with the Create command comes with an empty icon because there is no file in it yet. When I go into this folder and select the Create C# Script command, an image like the one below appears.

This is my new Script file. When I double-click on it, I get a window with the Script file created using Visual Studio, which is what we install when we install Unity on our computer. And here is my Script file:

This file comes with a class name. This class is the same as our file name. In this example I did not delete the default name, so it came with the name NewBehaviourScript. However, we make our own naming in the development environment: PlayerController, BallController, SpawnManager, etc.

The Start and Update methods that appear in the class come ready. We can write our code into these methods if necessary, or if not needed, we can delete them and create our own methods.

Script Content

We write our scripts in C# language and control the behaviour and interaction of game objects. For example, we can use functions provided by Unity such as transform.Translate to move an object or event methods such as OnCollisionEnterOnTriggerEnter to interact with other objects.

Let’s write a script to move our player horizontally and vertically.

Here we determine the movement speed of the player we want to move at the beginning.

Then we start writing our codes in the Update method that runs once in each frame.

Input.GetAxis("Horizontal"): We get the horizontal (left-right) input from the keyboard.

Input.GetAxis("Vertical"): We get vertical (forward-backward) input from the keyboard.

Vector3 moveDirection: We create a vector to determine the direction of movement. We fix the length of the vector to 1 by normalising it. This means converting the length of the vector to 1 while maintaining its direction. We do this especially in cases where the size (length) of the vector can take different values, because this way the direction of the vector becomes important, not its size.

transform.Translate(moveDirection * moveSpeed * Time.deltaTime): With this line, we can move the player using the specified move direction and speed. Time.deltaTime represents the time elapsed in each frame depending on the performance of the game and thus ensures that the movement is smooth and realistic.

We wrote our codes to move the actor, and we put our actor on our stage. So how does the program understand that these codes should move the actor? We do this as follows: By clicking Add Component in the Inspector section of the player character we have determined or by dragging the script to the Inspector section, we connect it to our player.

As we can see above, the variables and other information in the Script have been added to our Player. Here, since we set the moveSpeed variable as public, it appeared here with the assigned value of 5 and we can change this 5 value up or down if we want. If we had defined this variable as private, it would not appear here and therefore could not be changed.

It remains to test whether the codes we have written work correctly. We can do this by running the game, that is, by pressing play. If it does not work, we need to go back to the codes we wrote and check whether we have connected the Script to the correct component.

There is another important thing we need to know at this point. We pressed play to test the script and ran the game. From the example above, we made the moveSpeed variable 10 instead of 5. Of course, we can control what and how the change we made affects what we do, of course, this feature is already there for this. However, after running the game, that is, when we are in Play mode, any changes we make are not saved. So when we stop the game, we see that the variable is set back to 5. Let’s pay attention to this too.

As a result, Script programming has a fundamental role in the game development process in Unity. By controlling the behaviour and interaction of game objects, we can create the game mechanics we want. I hope it was useful.

Thanks for reading.

Selin.