- Home /
Touchscreen for unity
Hi guys i already finished my game but now i need to know how to make it touchscreen.I am using a character controller that only uses right,left and jump (2d game) and want to make it touchscreen but i have really no idea where to start to make it touchscreen.Do i just have to make gui textures and add a script to it? Can anybody give me some clues?thanks
Not sure that you finished your game if you still need to add touch controls. ;-)
Answer by dbrizov · Jun 10, 2014 at 10:12 AM
One way to do this is to create 3DText GameObjects for the left, right and jump key. You will then need to give them BoxCollider components. Once this is done you need to Raycast a ray to the touch position and check if you've hit one of the 3DText's colliders. If you hit the left 3DText, then you simply move the character to the left and so on.
Have a look at this pseudo-code. I Hope it helps:
public class PlayerController : MonoBevaviour
{
// Those 3 are the 3DTexts in the scene
private GameObject leftArrow;
private GameObject rightArrow;
private GameObject jumpKey;
private void Start()
{
// Find the 3DTexts in the scene
// Another way will be to make the game objects public and drag and drop them from the editor
this.leftArrow = GameObject.Find("Left Arrow"); // The name of the leftArrow 3DText is "Left Arrow"
this.rightArrow = GameObject.Find("Right Arrow");
this.jumpKey = GameObject.Find("Jump Key");
}
private void Update()
{
// If we have touched the screen
if (Input.touchCount > 0)
{
foreach (var touch in Input.touches)
{
// If the touch began, or moved, or is on the screen but stationary
if (touch.phase == TouchPhase.Began ||
touch.phase == TouchPhase.Moved ||
touch.phase == TouchPhase.Stationary)
{
Ray ray = Camera.main.ScreenPointToRay(touch.position);
RaycastHit hit;
float rayLength = 100.0f;
if (Physics.Raycast(ray, out hit, rayLength))
{
// If the ray hit the left arrow game object
if (hit.collider.gameObject == this.leftArrow)
{
// Move the player to the left
}
else if (hit.collider.gameObject == this.rightArrow)
{
// Move the player to the right
}
else if (hit.collider.gameObject == this.jumpKey)
{
// Make the player to jump
}
}
}
}
}
}
}
Answer by screenname_taken · Jun 10, 2014 at 10:44 AM
I'm a bit against using 3D text when possible as you get lots of extra draw calls. It really just needs a guitexture with a touch script. Or if you need a mesh, just a plane mesh with a script to always look towards the camera and a collider for ray casting.
Your answer
Follow this Question
Related Questions
Help with destroying guiRect? 0 Answers
Make more buttons appear, on button click. 1 Answer
scaling behaviour of the standard box texture? 0 Answers
Blurry Texture Help 5 Answers
reference Gui texture outside script 1 Answer