- Home /
How to make basic touch screen controls
Hey everyone, so i finally got my game on my phone to test. Up until now i have been using the left and right arrow key to move the player left and right and the space bar to jump. I want to add images to my canvas (a left arrow for moving left, a right arrow for moving right and a circle for jump) so when on the phone, the player can physically press the button and the character will act out what is pressed. Im just worried that by doing this, my walk animations will stop working. Here is the code I am working with. The code works perfectly with keyboard keys I assigned in Input Manager but if anyone can see what needs to get tweeked I really appreciate it :)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Player : MonoBehaviour {
public float maxSpeed = 3;
public float speed = 50f;
public float jumpPower = 150f;
public bool grounded;
private Rigidbody2D rb2d;
private Animator anim;
void Start () {
rb2d = gameObject.GetComponent<Rigidbody2D>();
anim = gameObject.GetComponent<Animator>();
}
void Update () {
anim.SetBool("Grounded",grounded);
anim.SetFloat("Speed", Mathf.Abs(rb2d.velocity.x));
if (Input.GetAxis("Horizontal") < -0.1)
{
transform.localScale = new Vector3(-1, 1, 1);
}
if (Input.GetAxis("Horizontal") > 0.1)
{
transform.localScale = new Vector3(1, 1, 1);
}
if (Input.GetButtonDown("Jump") && grounded)
{
rb2d.AddForce(Vector2.up * jumpPower);
}
}
void FixedUpdate() {
Vector3 easeVelocity = rb2d.velocity;
easeVelocity.y = rb2d.velocity.y;
easeVelocity.z = 0.0f;
easeVelocity.x *= 0.75f;
float h = Input.GetAxis("Horizontal");
//Fake friction / Easing the x speed of our player
if (grounded)
{
rb2d.velocity = easeVelocity;
}
//Moving the Player
rb2d.AddForce((Vector2.right * speed) * h);
//Limiting the Speed of the Player
if (rb2d.velocity.x > maxSpeed)
{
rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
}
if (rb2d.velocity.x < -maxSpeed)
{
rb2d.velocity = new Vector2(-maxSpeed, rb2d.velocity.y);
}
}
}
Answer by screenname_taken · Jul 25, 2017 at 09:19 PM
https://unity3d.com/learn/tutorials/s/mobile-touch You'd use a canvas, in it two arrow images for left and right, and when you touch those they can invoke a function in a script.