- Home /
Moving character with touch controls.
I am currently working on a 2D platformer and I am having issues with moving my character. I've exported this to Android as well. What I had originally were two separate buttons for movement back and forth using event triggers and that worked just fine. Well I was told to change that into one button so that the character can move back and forth without lifting your finger. Users should be able to move the character simply my moving their finger back and forth on the button. Any help on this issue is greatly appreciated. Thank you!
use touch phase.. http://docs.unity3d.com/ScriptReference/TouchPhase.html
Answer by Chris333 · Jun 17, 2015 at 07:47 AM
Hi,
i have a mobile game where you can move the player by moving the finger over the screen not depending if you are on a button. The following snippet should do that.
private Vector3 velocity = Vector3.zero;
public float smoothTime = 0.3F;
void FixedUpdate ()
{
Vector2 touchDeltaPosition = Vector2.zero;
//touch movement
if (Input.touchCount > 0)
{
// Get movement of the finger since last frame
touchDeltaPosition = Input.GetTouch(0).deltaPosition * speed;
}
Vector3 actualPosition = GetComponent<Rigidbody2D>().position;
Vector3 target = new Vector3(actualPosition.x + touchDeltaPosition.x, actualPosition.y + touchDeltaPosition.y, 0.0f);
GetComponent<Rigidbody2D>().position = Vector3.SmoothDamp(actualPosition, target, ref velocity, smoothTime);
}
To make it work with your UI button you could use the following method. It simply checks if the pointer with the given id is over a gameObject.
http://docs.unity3d.com/ScriptReference/EventSystems.EventSystem.IsPointerOverGameObject.html
I didnt tested this but it should work.
How would I go about incorporating IsPointerOverGameObject into the script. I've been messing around with it but can't get it to work properly.
The documentation Chris linked you to has a great example of how to use IsPointerOverGameObject. If you followed the documentation and still can't get it working please post some code from your script so we see what you are doing?
Your answer
Follow this Question
Related Questions
UI works in editor, but not on mobile device 1 Answer
[C#] Both button check with delay. 1 Answer
problem with button touch zone 0 Answers
how to change keyboard PC button to touch mobile (iOS, Andoird) button 1 Answer
why doesn't my touch-position conditional statements work for mobile app? 0 Answers