Hello friends
I am stuck with this script in which i want to move my player from left to right (ONLY HORIZONTALLY) by dragging it on screen.
By far i am able to move it by keyboard input on my desktop.
I am somewhat lost on how to achieve it.
Thanks in advance
using UnityEngine;
using System.Collections;
public class movement : MonoBehaviour {
Vector2 position;
public float speed;
void Start () {
position = transform.position;
}
void Update () {
float moveX = Input.GetAxis (“Horizontal”);
position.x += moveX * Time.deltaTime * speed;
position.x = Mathf.Clamp (position.x, -7.5f, +7.5f);
transform.position = position;
}
}
2185523–144911–movement.cs (397 Bytes)
using UnityEngine;
using System.Collections;
public class movement : MonoBehaviour {
Vector2 position;
public float speed;
void Start () {
position = transform.position;
}
void Update () {
float moveX = Input.GetAxis ("Horizontal");
position.x += moveX * Time.deltaTime * speed;
position.x = Mathf.Clamp (position.x, -7.5f, +7.5f);
transform.position = position;
}
}
Thanks for the code tags
So, you want to drag the player on the screen on the x-axis by using your mouse instead of your keyboard, right? Did you try out Input.GetAxis(“Mouse X”); ?
nope… i want to drag the player using touch controls (only on x axis)
i am making it for android/ios
So your player is for example in the center of the screen. Now you wanna drag him from center to right for example and he will move to the right with some latency? You should check out some touch tutorials and maybe explain, how you want to move your character exactly. Like, touch on a point and move there, or drag to the right and move to the right depending on touch begin and end?
yes, basically i am making a brick breaker game , in which i want to control the paddle with touch-drag movement from left to right.
Did you check the API and tried to fiddle around with it?
There you got the position of the touch and you can use that Vector2 to animate your character.
i did see that. Issue with me is that i am not from a programming background. Art is more of my thing, thats why i am having difficulty in this.
Try this. Not tested but could keep you going:
using UnityEngine;
using System.Collections;
public class movement : MonoBehaviour {
Vector2 charPosition;
public float speed;
void Start () {
charPosition = transform.position;
}
void Update () {
float moveX ;
for (var i = 0; i < Input.touchCount; ++i) {
Touch touch = Input.GetTouch(i);
if (touch.phase == TouchPhase.Began) {
moveX = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 0)) ;
charPosition.x += moveX * Time.deltaTime * speed;
charPosition.x = Mathf.Clamp (charPosition.x, -7.5f, +7.5f);
transform.position = charPosition;
}
}
}
}
I just changed the position var to charPosition, as you should never use API specific keywords like this for variables 
thanks for help
i will try this out