How to replace keyboard inputs with touch inputs.
Hey guys, I am more of a designer not a programmer so i tried out this video tutorial on how to make a 2D fighting game. According to the inputs manager the events on the x, y axis are controlled with specific keys. But i want this game to be playable on android devices so i need UI buttons i suppose ? How can i kind of make a function that uses the already working code for PlayerControl and call them on button tap ? Or maybe there is another solution ? I need 5 buttons: left, right, jump, left punch, right punch. My number one target is to follow the line of this code because have few to zero skills in C#. I am using Unity 5.3.4f1, btw i think there might be some problems with UI buttons, not very sure.This is the code i currently use. Any help is very appreciated ! Thanks
using UnityEngine; using System.Collections;
public class PlayerControl : MonoBehaviour {
public int PlayerNumber = 1;
Transform enemy;
Rigidbody2D rig2d;
Animator anim;
float horizontal;
float vertical;
public float maxSpeed = 25;
Vector3 movement;
bool crouch;
public float Jumpforce = 20;
public float jumpDuration = .1f;
float jmpDuration;
float jmpForce;
bool jumpKey;
bool falling;
bool onGround;
void Start()
{
rig2d = GetComponent<Rigidbody2D>();
anim = GetComponentInChildren<Animator>();
}
void FixedUpdate()
{
//#if !UNITY_ANDROID && !UNITY_IPHONE && !UNITYWINRT
horizontal = Input.GetAxis("Horizontal" + PlayerNumber.ToString());
vertical = Input.GetAxis("Vertical" + PlayerNumber.ToString());
//#endif
Vector3 movement = new Vector3(horizontal, 0, 0);
crouch = (vertical < -0.1f);
if (vertical > 0.1f)
{
if (!jumpKey)
{
jmpDuration += Time.deltaTime;
jmpForce += Time.deltaTime;
if (jmpDuration < jumpDuration)
{
rig2d.velocity = new Vector2(rig2d.velocity.x, jmpForce);
}
else
{
jumpKey = true;
}
}
}
if (!onGround && vertical < 0.1f)
{
falling = true;
}
if (!crouch)
rig2d.AddForce(movement * maxSpeed);
else
rig2d.velocity = Vector3.zero;
}
void OnGroundCheck()
{
if (!onGround)
{
rig2d.gravityScale = 5;
}
else
{
rig2d.gravityScale = 1;
}
}
void Update()
{
UpdateAnimator();
OnGroundCheck();
}
void UpdateAnimator()
{
anim.SetBool("OnGround", this.onGround);
anim.SetBool("Falling", this.falling);
anim.SetBool("Crouch", crouch);
anim.SetFloat("Movement", Mathf.Abs(horizontal));
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.collider.tag == "Ground")
{
onGround = true;
jumpKey = false;
jmpDuration = 0;
jmpForce = Jumpforce;
falling = false;
}
}
void OnCollisionExit2D(Collision2D col)
{
if (col.collider.tag == "Ground")
onGround = false;
}
}
Answer by Jason2014 · May 02, 2016 at 02:45 PM
You have to write additional code for "Touch Input". See there: Adding Mobile Controls in Roguelike project
Your answer
![](https://koobas.hobune.stream/wayback/20220612075838im_/https://answers.unity.com/themes/thub/images/avi.jpg)