I am trying to use onscreen buttons to go up and down a ladder the current code works just fine with the W and S keys, but I'm not quite sure how to put the code into seperate methods so the touch can access it.
I was researching accessing the colliders on the player and the ladder from a separate script but they said it couldn't be done. I also tried assigning the Keycode to a separate variable inside a method then assigning this method to the onscreen keys but that didn't work.
public void OnTriggerStay2D(Collider2D other)
{
if (other.tag == "Player" && Input.GetKey(KeyCode.W))
{
other.GetComponent<Rigidbody2D>().velocity = new Vector2(0, speed);
}
else if (other.tag == "Player" && Input.GetKey(KeyCode.S))
{
other.GetComponent<Rigidbody2D>().velocity = new Vector2(0, -speed);
}
else{
other.GetComponent<Rigidbody2D>().velocity = new Vector2(0, 1);
}
}
Not enough details to work from but, unless I misunderstood you completely, if all you want to do is to move the player using screen touch input instead of the keyboard input then the simplest way to handle it without changing too much in your working code would be to simply assign Boolean variables to the input conditions and check for them instead of the keyboard input inside the function you shared.
So, for example, the function would look something like:
public void OnTriggerStay2D(Collider2D other)
{
if (other.tag == "Player" && UpKeyPressed)
{
other.GetComponent<Rigidbody2D>().velocity = new Vector2(0, speed);
}
else if (other.tag == "Player" && DownKeyPressed)
{
other.GetComponent<Rigidbody2D>().velocity = new Vector2(0, -speed);
}
else{
other.GetComponent<Rigidbody2D>().velocity = new Vector2(0, 1);
}
}
Where UpKeyPressed and DownKeyPressed are Boolean variables which can be set to true/false when you touch the screen based keys or whatever is the UI for the touch based input.