Below, is the code that I attached to the gameObject that I wanted to affect.
using UnityEngine;
using System.Collections;
public class Drag : MonoBehaviour {
private Vector2 screenPoint;
void OnMouseDrag()
{
Vector2 curScreenPoint = new Vector2(Input.mousePosition.x, 0);
Vector2 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint);
transform.position = curPosition;
}
}
Originally, I had set “Vector2 curScreenPoint new Vector2(Input.mousePosition.x, Input.mousePosition.y);”; however, I changed the y parameter to 0 because I didn’t want my gameObject to move in the y direction only the x direction.
Thanks in advance.
Check to see if the Z position is zero and behind your camera.
Maybe is that setting curScreenPos.y = 0 doesn’t mean you don’t have a change in this position. In this case your GameObject will be set at the bottom of your screen.
if you want, that your drag only changes X Position of your current transform you have to do →
void OnMouseDrag()
{
Vector2 curPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = new Vector3(curPosition.x, transform.position.y, transform.position.z);
}
so your drag will only affect x
1 Like
Thank you, this worked great. Now I need to figure out how to make my character move in this way when I click and drag on any part of the screen. If I attach this script to the main camera and rewrite this script to move the character from there, would that work?
Yes it would work, if you set the curPosition x and y aos transform.position your charakter will follow your mouse.