- Home /
 
Making a ball follow my mouse only on the y axis, and let it automatically move on x axis 2D
im trying to make a 2d game where a circle follows my mouse up and down and goes on a straight way on the +x axis, but when i drag the circle (in the game) he goes back to the starting point on the x axis. but i want him to just go further on the x axis.
public class PlayerMovement : MonoBehaviour {
 private float dragPosition;
 public float moveSpeed;
 private Rigidbody2D myRigidbody;
 void Start () {
     myRigidbody = GetComponent<Rigidbody2D>();
     Vector3 mousePosition = Input.mousePosition;
 }
 
 void Update () {
     myRigidbody.velocity = new Vector2(moveSpeed, 0);
 }
 void OnMouseDrag()
 {
     Vector3 target = new Vector3(0.0f, dragPosition, 0.0f);
     dragPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition).y;
     transform.position = Vector3.MoveTowards(transform.position, target, 100 * Time.deltaTime);
 }
 
               }
Answer by VahanSardaryan · Jan 13, 2019 at 06:10 PM
Change this dragPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition).y; to this dragPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition.y);
If you want that all works correctly do not name the variables exactly like his definition.For example mousePosition.
Answer by MT369MT · Jan 13, 2019 at 06:14 PM
Hi, Your problem is that the target x position is 0. Instead, it should be transform.position.x
Change your code like this:
 dragPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition).y;
 Vector3 target = new Vector3(transform.position.x, dragPosition, 0.0f);
 transform.position = Vector3.MoveTowards(transform.position, target, 100 * Time.deltaTime);
 
              Your answer
 
             Follow this Question
Related Questions
Top down movement and rotation 2 Answers
Shooting in direction of mouse cursor 2d 5 Answers
Shooting at mouse position in 2d from a Child Object 0 Answers
MouseLook - Min & Max Problem 2 Answers