- Home /
Question by
sandunjanitha8 · Aug 14, 2020 at 05:18 AM ·
unity 5cameramovementgameobject
How can i Drag 3d Object x axis only when mouse drag anywhere screen?
I'm using this script.But this working when click and drag on object. I need drag anywhere of the screen.
void OnMouseDown()
{
mZCoord = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
// Store offset = gameobject world pos - mouse world pos
mOffset = gameObject.transform.position - GetMouseAsWorldPoint();
}
private Vector3 GetMouseAsWorldPoint()
{
// Pixel coordinates of mouse (x,y)
Vector3 mousePoint = Input.mousePosition;
// z coordinate of game object on screen
mousePoint.z = mZCoord;
// Convert it to world points
return Camera.main.ScreenToWorldPoint(mousePoint);
}
void OnMouseDrag()
{
transform.position = new Vector3(GetMouseAsWorldPoint().x + mOffset.x, transform.position.y, transform.position.z);
//transform.position = GetMouseAsWorldPoint() + mOffset;
}
Comment
Answer by ben-rasooli · Aug 14, 2020 at 01:05 PM
void Update()
{
if (Input.GetMouseButtonDown(0))
{
mZCoord = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
// Store offset = gameobject world pos - mouse world pos
mOffset = gameObject.transform.position - GetMouseAsWorldPoint();
}
if (Input.GetMouseButton(0))
{
transform.position = new Vector3(GetMouseAsWorldPoint().x + mOffset.x, transform.position.y, transform.position.z);
//transform.position = GetMouseAsWorldPoint() + mOffset;
}
}
Vector3 GetMouseAsWorldPoint()
{
// Pixel coordinates of mouse (x,y)
Vector3 mousePoint = Input.mousePosition;
// z coordinate of game object on screen
mousePoint.z = mZCoord;
// Convert it to world points
return Camera.main.ScreenToWorldPoint(mousePoint);
}
Your answer
Follow this Question
Related Questions
how are Mathf.SmoothDamp and Mathf.SmoothStep different 1 Answer
Camera movement question 1 Answer
My text don't appear in Game Window, help 1 Answer
Move Rigidbody along curve 1 Answer
Movement Backwards is Slower 0 Answers