I am making a 2D platformer game, and I can now controll the player with the arrowkeys. Now I want to controll the player using buttons on the screen, so that it can be used on IOS/android. I only need the player to walk left and right. Does anyone have code that is fully functional that can fix my problem?
I recommend separating the logic for your input handling and player motion controller into something like (pseudocode)
if input pressed space:
tell player motion controller to jump
if input pressed left:
tell player motion controller to go left
if input pressed right:
tell player motion controller to go right
in Update() of a separate object in the scene.
This separate input handler should have a reference to the player motion controller by a scene-level (not prefab-level) serialized reference (i.e. in the inspector editor window) or by one-shot calls to FindGameObjectsWithTag() + GetComponent() / FindObjectsOfType()in Start() or in a lazy initializer in accessor, etc. – exactly how is up to you.
And then in your motion controller have (pseudocode)
This will allow you to control the player motion controller independent of the Unity input classes. Now you can use, and more importantly, test it separately.
I have now managed to get this working!! The only issue that I have now is for some reason my jump and attack animations are playing twice but for your issue that isn’t a problem. Using a combination of all the previous answers I have my player control script with Touch functions and then my Touch controls script with the bool references in it.
The bit you need in the Player Script
public float movespeed;
public bool moveleft;
public bool moveright;
public Rigidbody2D rb;
private float movedirection;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
public void InputHandler()
{
movedirection = Input.GetAxisRaw("Horizontal");
}
public void TouchMove(float movedirection)
{
if (grounded && moveleft)
{
rb.velocity = new Vector2(-movespeed, rb.velocity.y);
}
else if (grounded && moveright)
{
rb.velocity = new Vector2(movespeed, rb.velocity.y);
}
}
and then the separate Touch Controls script
private "Your Control Script Name" player;
// Use this for initialization
void Start()
{
player = FindObjectOfType<"Your Control Script Name">();
}
public void LeftArrow()
{
Debug.Log("Moving Left");
player.moveleft = true;
player.moveright = false;
}
public void RightArrow()
{
Debug.Log("Moving Right");
player.moveright = true;
player.moveleft = false;
}
public void ReleaseArrow()
{
player.moveright = false;
player.moveleft = false;
}
and then create 2 UI images and an empty parent object to hold them. Add the Touch script to the parent object and then add 2 Event triggers to each image for OnPointerDown + Up and drag the parent object into where it says ‘None’ in the Editor, then select the relevant functions to call.