Hi, I’m relatively new to Unity as well as C-Sharp, and im trying to make a game for mobile in which there are 3 controls on screen. An arrow facing right, one facing left, and one facing up.
What I wish to achieve is when the player holds their finger on the right arrow button (IE GetMouseButton(0)) The in-game player will move to the right at a certain rate.
I have been searching around trying to find answers, and most come to the idea of Raycasting, which I have never used before. Basically, if someone could tell me how to do something only when the user holds the mouse button down on ONE SPECIFIC OBJECT, something will happen. Also, the buttons never move, they will stay on screen at all times.
Just for some more information, this is a 2D based game, and I have a Box Collider 2D on each of my 3 buttons, if that makes a difference. Thanks!
Well you didn’t specified what type are the arrows.
If they are sprites and have a collider atached to them you can do something like this:
Vector3 tmpPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (collider2D == Physics2D.OverlapPoint(tmpPos) && Input.GetMouseButton(0) == true)
{
//code here
}
If you say they will never change position I suggest to use GUITexture instead because they will look the same on every resolution and stay in the same position whatever the resolution or aspect ratio. For GUITexture you can use this:
if (guiTexture.HitTest(Input.mousePosition) && Input.GetMouseButton(0) == true)
{
//code here
}
You said you want this to be for mobile so for touch controls you do like this:
if (Input.touchCount > 0)
for (int i = 0; i < Input.touchCount; i++)
{
Touch touch = Input.GetTouch(i);
//here you copy-paste the above code and instead of "Input.mousePosition" put "touch.position"
}