- Home /
Unity 4, Multitouch/FingerId and Android
I have an issue with creating 2 joysticks to control my game. There's a left and a right joystick, both have a little dot in the middle that's supposed to follow player's finger. It does work, but only for 1 joystick (either one). Once I try to control both at the same time the little dot from a joystick I used second follows the finger I pressed down first on the first joystick. From what I could tell the issue lies in the touch.fingerId function. I read somewhere that it was broken in Unity 3.X.X, was it fixed in Unity 4?
I could write it without the use of FingerId, but that would limit joystick's functionality (they would only work when the finger is directly on them, while the use of fingerId should allow me to track the movement outside of the joystick's graphic and have it work properly, the only requirement being that the touch began inside the graphic). Here's my code:
using UnityEngine;
using System.Collections;
public class Joysticks : MonoBehaviour {
PlayerStats playerStats;
int fingerId;
bool stickActive;
GameObject attachedButton;
void Start () {
playerStats = GameObject.Find("Player").GetComponent<PlayerStats>();
switch(this.transform.name){ //CHECKS WHICH JOYSTICK IT IS AND ASSIGNS VALUES ACCORDINGLY
case "LeftStick":
transform.localPosition = leftStick;
attachedButton = transform.parent.transform.FindChild("LeftStickButton").transform.gameObject;
attachedButton.transform.position = transform.position;
break;
case "RightStick":
transform.localPosition = rightStick;
attachedButton = transform.parent.transform.FindChild("RightStickButton").transform.gameObject;
attachedButton.transform.position = transform.position;
break;
}
}
void Update () {
if (stickActive){
foreach (Touch touch in Input.touches){
if(touch.fingerId==fingerId){
attachedButton.transform.localPosition = touch.position;
}
}
}
}
void OnPress(){ //THIS IS CALLED WHENEVER ONE OF THE JOYSTICKS IS TOUCHED AND TRIGGERS STUFF IN UPDATE()
stickActive = !stickActive;
if (stickActive){
foreach (Touch touch in Input.touches){
if(Vector2.Distance(touch.position, transform.position)<150 && touch.phase == TouchPhase.Began){
fingerId = touch.fingerId;
}
}
} else {
attachedButton.transform.position = transform.position; //RESETS DOT'S POSITION WHEN
}
}
}
Answer by hemik · Aug 29, 2013 at 06:22 AM
Alright, I solved it, I had to change transform.position into localPosition in the Vector2.Distance check
Your answer
Follow this Question
Related Questions
Andriod Multitouch with joystick 1 Answer
How to make first person game with joysticks? 0 Answers
Need to Put buttons on Iphone/Android game 1 Answer
Joystick won't move in Unity 0 Answers
How to use the joystick.js in unity3d?? 0 Answers