I’m working on a game where the character is controlled very simply by touching and dragging anywhere on the screen. Since upgrading to Unity 5, the character will randomly speed up and slow down, at times appearing to teleport across the screen even though I’m dragging my finger at a relatively constant speed.
The simplest version of the code looks like this:
void Update() {
if (Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Moved) {
Touch touch = Input.touches[0];
Vector3 t = new Vector3(touch.deltaPosition.x * 10f * Time.deltaTime, touch.deltaPosition.y * 10f * Time.deltaTime, 0.0f);
gameObject.transform.Translate(t);
}
}
(In my game, I’ve replaced the “10f” values with an adjustable “sensitivity” setting.)
That’s the code that was working in my 4.6 project. Since looking into this issue, I found one suggestion to check against Touch.deltaTime, which makes the code look like this:
void Update() {
if (Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Moved)
{
Touch touch = Input.touches[0];
float dt = Time.deltaTime / touch.deltaTime;
if (dt == 0 || float.IsNaN(dt) || float.IsInfinity(dt))
dt = 1.0f;
Vector2 fixedTouch = touch.deltaPosition * dt;
Vector3 t = new Vector3(fixedTouch.x * 10f * Time.deltaTime, fixedTouch.y * 10f * Time.deltaTime, 0.0f);
gameObject.transform.Translate(t);
}
}
However, that didn’t seem to have any effect – at least, it didn’t solve my issue. I’ve created a new 2D project which contains only the default Main Camera and a Sprite, to which I’ve attached the script above. I can’t find any combination of settings that stops the sprite from moving erratically when I drag it around the screen.
I’m testing this on a Nexus 5 running Android version 5.0.1. When I upgraded to Unity 5 I had to upgrade my JDK, but this doesn’t seem to be the cause of the issue as the sprite moves smoothly after creating exactly the same test project in Unity 4.6. One thing I did notice is that the deltas seem larger in 4.6, so that I had to lower the “10f” to “5f” to get the sprite to move at approximately the same speed so I could watch it for jerkiness without it jumping off-screen.
So, with that final test – exactly the same simple project running in 4.6 and 5.0 – I think I’m safe adding the “bug” tag to this post. However, I’m relatively new to Unity, so my questions are:
- Am I doing anything wrong in my code?
- Has anyone else seen this issue? Can you reproduce it on other Android devices / iPhones / etc.?
- Can you think of anything for me to try?
- Is there any other information I should include in my bug report?
I’ll go ahead and file a proper bug report, but I figured I would post this here to see if anyone else is experiencing this as well. Oh, and let me know if this isn’t the right place for this as I’m on the fence about whether to post this to Answers or the Forums! Thanks for your help!