- Home /
How can I move my 2D main player up and down by clicking and dragging him up or down?
Hello,
What I want to do is so simple in theory but not working in practice. I have a 2D game with a player that can only move along the Y-axis (up and down). Right now he moves up and down with the 'W' and 'S' keys but I want him to move up and down with a mouse click and drag up or down. Thank you in advance for anyone who can help.
Answer by davidcox70 · Apr 09, 2018 at 11:34 PM
Add this to your object, ensuring it has a collider (which is needed to receive the mouse event);
//
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class dragMe : MonoBehaviour {
private Vector3 screenPos;
private Vector3 offset;
void OnMouseDown(){
// work out the target object is on the screen
screenPos = Camera.main.WorldToScreenPoint (transform.position);
// store the starting position of the drag
offset=transform.position-Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y,screenPos.z));
}
void OnMouseDrag(){
// convert just the Y position Vector3 currentScreenPos = new Vector3 (screenPos.x, Input.mousePosition.y, screenPos.z);
// add the resulting tranform transform.position = Camera.main.ScreenToWorldPoint (currentScreenPos) + offset;
}
}
Hey thank you for your time! So I tried your suggested code and it works except that when I click on my player object, his transform shifts and he gets moved to the left and also pushed back on the z axis. The mouse drag works and I'm able to move him up and down which is great, but is there a way I can keep the players transform the same?
i fixed it so that on mouse click doesn't change the transform, however, when I drag the game object up and down, I notice that the players Z transform is changing as well as the Y's. I cant seem to get just the Y transform to change
Hello, It shouldn't change the Z position. But just to make sure, you could make this change. Change the line:
transform.position = Camera.main.ScreenToWorldPoint (currentScreenPos) + offset;
to:
Vector3 newPos=Camera.main.ScreenToWorldPoint (currentScreenPos) + offset;
transform.position = new Vector3(transform.position.x,newPos.y,transform.position.z);
This means only the Y position of the transform is changed. X and Z are copied.
That solved the issue I was having. Thank you so much for taking the time to help me out. I really appreciate it!