- Home /
Move JoyStick Together With Camera
Hey guys, I am making unity mobile game and I made a joystick to control my characters movement, the issue is my camera tracks the player, and whenever the camera moves joystick is left behind and after some time i can't even see it, so i was wondering is there a way to move my joystick together with the camera or relative to the camera so it's always at the same spot on the screen, here is my joystick code. I also have same joystick for shooting in another script if that matters, but its mostly a copy of this just for different side of screen.
if (Input.touchCount > 0)
{
if (Outer == null && Input.touchCount > 1)
{
for (int i = 0; i < Input.touchCount; i++)
{
if (Input.GetTouch(i).position.x <= Screen.width / 2)
{
t = Input.GetTouch(i);
break;
}
}
}
if (Input.touchCount == 1)
{
t = Input.GetTouch(0);
}
for (int i = 0; i < Input.touchCount; i++)
{
if (Outer != null && t.fingerId == Input.GetTouch(i).fingerId)
{
t = Input.GetTouch(i);
}
}
if (t.phase == TouchPhase.Began && t.position.x <= Screen.width / 2 && Outer == null && t.position.x != 0)
{
A = Camera.main.ScreenToWorldPoint(t.position);
id = t.fingerId;
Outer = Instantiate(OuterPre, new Vector3(A.x, A.y), this.transform.rotation);
middle = Instantiate(middlePre, new Vector3(A.x, A.y), this.transform.rotation);
}
if (t.phase != TouchPhase.Ended && Outer != null && id == t.fingerId )
{
Touched = true;
B = Camera.main.ScreenToWorldPoint(t.position);
}
else
{
Touched = false;
t = new Touch();
Destroy(Outer);
Destroy(middle);
}
}
}
void FixedUpdate()
{
if (Touched)
{
Vector2 offset = B - A;
Vector2 direction = Vector2.ClampMagnitude(offset, 1f);
middle.transform.position = new Vector2(A.x + direction.x, A.y + direction.y);
Move(direction);
}
}
Answer by justasxz · Aug 13, 2020 at 12:13 AM
Figured it out myself, leaving this if somebody need's it in the future. I set the Outer circle as a child to camera and now it moves relative to the camera, and after that i just set A vector equal to current Outer circle position, and middle circle adjusts itself.
Your answer
Follow this Question
Related Questions
Changing the axes of a joystick based on the position of the camera? 1 Answer
How do you move the camera relative to the direction it is currently facing? 1 Answer
how to rotate GameObject towards joystick 1 Answer
How do I access a gamepad's joystick position? 1 Answer
Expand script to stop camera from following player 2 Answers