I
I
Ivan Aleksandrovsky2018-11-13 12:07:45
Mobile development
Ivan Aleksandrovsky, 2018-11-13 12:07:45

How to implement control on the phone?

Hello, I am writing my first game on a mobile phone.
Recently, it was necessary to make the control of the hero so that when you click on the model, it follows the finger across the screen.
On the Internet, I found a script that works fine on a PC, but not on a phone.
Tell me how to change it or what needs to be added to make the control work on the phone?

The script itself:
using UnityEngine;
using System.Collections;

[System.Serializable]
public class Boundary
{
    public float xMin, xMax, zMin, zMax;
}

public class Player_Control : MonoBehaviour
{
    public float speed;
    public float tilt;
    public Boundary boundary;
    Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
        rb.velocity = movement * speed;

        rb.position = new Vector3
        (
            Mathf.Clamp(rb.position.x, boundary.xMin, boundary.xMax),
            0.0f,
            Mathf.Clamp(rb.position.z, boundary.zMin, boundary.zMax)
        );

        rb.rotation = Quaternion.Euler(rb.velocity.z * tilt, 0.0f, rb.velocity.x * -tilt);
    }
}


Thank you in advance for your help

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GreatRash, 2018-11-13
@GreatRash

The Input class has many different methods besides .GetAxis(). For example .GetTouch(), which you will need if you are implementing a virtual joystick in the game. Or, for example Input.gyro, it will provide access to the gyroscope if you want to control the hero by tilting the phone in different directions. There are many interesting examples in the documentation for the class. Be sure to read it.

A
Alice, 2018-11-19
@Elf-Cat

You can create control buttons (left, right, up, down), then write scripts for them that call a function in the player's script and create 4 functions specifically for them that will move the player

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question