N
N
novichekvunity2021-01-25 17:30:56
Unity
novichekvunity, 2021-01-25 17:30:56

How to make a touch on unity?

using UnityEngine;
using System.Collections;

public class chel : MonoBehaviour
{
public Rigidbody2D rb;
public float jumpForce;
public float speed;

private void Update()
{
if (Input.GetKey(KeyCode.A))
{
transform.Translate(Vector2.left * speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D))
{
transform.Translate(Vector2.right * speed * Time.deltaTime);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
rb.velocity = new Vector2(0, 0);
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}

}
I was trying to make a game like doodle jump for android, but in the movement I put the buttons a (left) and d (right). How to make it possible to move by tapping on the smartphone screen?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Bogdan Erolskiy, 2021-01-26
@B-Erolskiy

Track a panel click using the IPointerEnterHandler , IPointerExitHandler interfaces attached to the object's script. The parameter of the methods implemented by these interfaces will be PointerEventData , using its property eventData.pressPosition.x, you can understand where the click was made.
Accordingly, it remains to calculate whether there was a click on the left or right side of the screen. It's very easy to do this:

bool isRightClick = eventData.pressPosition.x > Screen.width / 2;
bool isLeftClick = eventData.pressPosition.x < Screen.width / 2;

Screen.width, of course, should be cached.
Accordingly, if you click on the left side of the screen, we process the movement to the left, and vice versa.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question