I have the following code it works, but I don't know how it works.
This is the code I found:
void Update()
{
#if UNITY_ANDROID
if(Input.touchCount>0 && Input.GetTouch(0).phase == TouchPhase.Moved )
{
Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
float offset = touchDeltaPosition.x * 40f / 18 * Mathf.Deg2Rad;
transform.position += new Vector3(0f, 0f, offset);
transform.position = new Vector3(0f, 0f, Mathf.Clamp(transform.position.z, -7.1f, 7.1f));
}
#endif
}
I need to move the player along the axis by touch, for example, like in the game Cube Surfer!
What I want to get (I used android emulator):
The code I wrote works well at 720x1280, but if you set the resolution to 1440x2960, the controls become too sharp. I know why this is happening because touch.delta is getting too big.
My code:
if (Input.touchCount > 0)
{
var t = Input.GetTouch(0);
var delta = t.deltaPosition;
if (delta != Vector2.zero)
{
var offset = transform.position;
offset.x += delta.x * Sensitivity * Time.deltaTime;
offset.x = Mathf.Clamp(offset.x, -4f, 4f);
transform.position = offset;
}
}
How to fix it?
ScreenToWorldPoint this does not fit because the player moves along a spline.
Thank for help
* 40f / 18
are what we call "Magic Numbers" - so named because it's difficult for anyone who didn't write the code originally to infer why those particular values are appropriate for this job - they're just "magic". I would say, if you don't understand this code, do not use it. It will cause you problems down the line if you need to modify it but don't understand what you're modifying. Instead, try editing your question to describe the behaviour that you need, and ask about how to achieve it. Then we can give you new code to achieve that end, and explain to you how it does it. \$\endgroup\$