- Home /
how to convert keyboard controls into touch controls?
I am creating a 2d game that has the player move from left to right and the other way around on the ground. I am currently using this:
if (Input.GetKey(moveLeft)) {
rigidbody2D.velocity.x = 2;
} else if (Input.GetKey(moveRight)) {
rigidbody2D.velocity.x = -2;
} else {
rigidbody2D.velocity.x = 0;
}
as code to move the object left and right. I've been googling a bit and found something about input.touch or so but nothing to get me going. I'd like some help on how to make this game so that when a player touches the object it will move along with the finger on the x axis. (so you can "slide" the object from left to right)
What part of your question is not answered by https://www.google.co.uk/search?q=unity+touch+tutorial ?
change the position of the object to the position of the touch. And restrict it in x-axis only.
using the following code:
if (Input.touchCount > 0 &&
Input.GetTouch(0).phase == TouchPhase.$$anonymous$$oved) {
// Get movement of the finger since last frame
var touchDeltaPosition:Vector2 = Input.GetTouch(0).deltaPosition;
// $$anonymous$$ove object across XY plane
transform.Translate (-touchDeltaPosition.x * speed,
-touchDeltaPosition.y * speed, 0);
}
$$anonymous$$y object vanishes as soon as I touch the screen. where did I mess up?
(speed is set to 0.1)
Answer by Jort · Nov 18, 2014 at 08:35 PM
I found a solution:
void Update () {
if (Input.touchCount > 0) {
// The screen has been touched so store the touch
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Stationary || touch.phase == TouchPhase.Moved) {
// If the finger is on the screen, move the object smoothly to the touch position
Vector3 touchPosition = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 10));
touchPosition.y = transform.position.y;
transform.position = Vector3.Lerp(transform.position, touchPosition, 20 * Time.deltaTime);
}
}
}
This is the only script with which my object doesn't disappear. If you wish to enable movement on the y axis as well just delete "touchPosition.y = transform.position.y;" If you wish to increase the speed at which the object follows the touch just increase the number 20, for a lower speed you can ofcourse decrease the number.
Answer by psycocrusher · Nov 18, 2014 at 06:47 PM
I am using this:
https://www.assetstore.unity3d.com/en/#!/content/14695
it converts keyboard, touch, joysticks, vita etc...
Your answer
Follow this Question
Related Questions
Converting Input.getAxis("Horizontal") to touch screen input. 0 Answers
How to get Horizontal axis value to 0 instantly after releasing the positive button!!!! 0 Answers
How can I smooth out and unlock the movement with the input system? 0 Answers
Something weird with my input system 1 Answer
Cannot Jump While Moving Diagonally 1 Answer