- Home /
Move Camera with touch (andoid)
Good day everyone, I've a question about touch input and using it to move my camera. My goal is to move the camera, which shows everything from above, with touch. So if my finger swipes up in a value of 1, the camera swipes down in a value of 1. So you move it like moving the map in google maps.
This code is in the update-section of my camera.
if (Input.touchCount == 0)
{
hold = false;
}
if (!hold) //wenn noch nicht gehalten, dann
{
if (Input.touchCount == 1) //überprüfe, of ein kontakt
{
hold = true;
startPos = Camera.main.ScreenToViewportPoint(Input.touches[0].position);
}
else if (Input.touchCount == 2) //überprüfe, ob zwei kontakte (ZOOM)
{
}
else
{
}
}
else //wenn schon gehalten wird, dann
{
if (Input.touchCount == 1)
{
Vector2 MoveVector = new Vector2(startPos.x - Camera.main.ScreenToViewportPoint(Input.touches[0].position).x, startPos.y - Camera.main.ScreenToViewportPoint(Input.touches[0].position).y);
transform.Translate(MoveVector * Time.deltaTime * 20);
}
}
I know, this is maybe hard to understand what I want (because I'm too stupid to tell you correctly), but I'm very happy about every answer :)
Have a nice day dudes!
Answer by xxmariofer · Mar 03, 2019 at 08:27 PM
hello test this code and tell me if it was what you were searching for
Vector2 MoveVector;
// Start is called before the first frame update
void Update()
{
if (Input.touchCount == 0)
{
if (hold)
{
MoveVector = new Vector2(startPos.x - Camera.main.ScreenToViewportPoint(Input.touches[0].position).x, startPos.y - Camera.main.ScreenToViewportPoint(Input.touches[0].position).y);
hold = false;
}
}
else
{
if (Input.touchCount == 1 && !hold) //überprüfe, of ein kontakt
{
hold = true;
startPos = Camera.main.ScreenToViewportPoint(Input.touches[0].position);
}
else if (Input.touchCount == 2) //überprüfe, ob zwei kontakte (ZOOM)
{
}
else
{
}
}
transform.Translate(MoveVector * Time.deltaTime * 20);
}
Hey, thank you for your help, but I get errors if I touch the screen. It says:
IndexOutOfRangeException: Index was outside the bounds of the array. CameraBehavior.Update () (at Assets/Scripts/Data/CameraBehavior.cs:25)
In your Code It's line 10.
But thank you anyways :)
oh i see thats because i am accessing to the touch number 1 when there are no touches my fault. try this create a new var called endPos
void Update()
{
if (Input.touchCount == 0)
{
if (hold)
{
$$anonymous$$oveVector = new Vector2(startPos.x - endPos.x, startPos.y - endPos.y);
hold = false;
}
}
else
{
if (Input.touchCount == 1 && !hold) //überprüfe, of ein kontakt
{
hold = true;
startPos = Camera.main.ScreenToViewportPoint(Input.touches[0].position);
}else if(Input.touchCount == 1 && hold)
{
endPos = Camera.main.ScreenToViewportPoint(Input.touches[0].position);
}
else if (Input.touchCount == 2) //überprüfe, ob zwei kontakte (ZOO$$anonymous$$)
{
}
else
{
}
}
transform.Translate($$anonymous$$oveVector * Time.deltaTime * 20);
}