- Home /
How will i drag my object only x and y axis?
Hi All,
I am new to unity 3d. I have a stop watch.
My task is i want to drag my stop watch in the hole scene . I wrote the code for x,y axis moving of the stop watch. but that is not moving.
My code is:
using UnityEngine;
using System.Collections;
public class Moused : MonoBehaviour {
public float sensitivity = 0.02f;
private Vector3 v3Prev;
void OnMouseDrag () {
if (Input.GetMouseButtonDown(0)) {
v3Prev = new Vector3(Input.mousePosition.x,Input.mousePosition.y,0);
}
if (Input.GetMouseButton (0)) {
Vector3 newPos = transform.position;
newPos.x = newPos.x + (Input.mousePosition.x - v3Prev.x) * sensitivity;
newPos.y = newPos.y + (Input.mousePosition.y - v3Prev.y) * sensitivity;
transform.position = newPos;
v3Prev = newPos;
}
}
}
I don't know the problem for moving. i added box collider to the stop watch.
can i get a solution. or any help
Thanksℜgards
Shankar
There are four coordinate systems in Unity: world, viewport, GUI, and screen. Input.mousePosition is in Screen coordinates. Your game object is in world coordinate. One way to convert between the two is Camera.ScreenToWorldPoint(). Note the 'Z' parameter of this function is the distance in front of the camera. There are lots of posts on drag and drop in UA.
Answer by cwkx · May 16, 2013 at 09:44 AM
As robertbu said, Input.mousePosition is in "screen space" but you want to drag in "world space". Therefore:
using UnityEngine;
using System.Collections;
public class DragScript : MonoBehaviour {
private Vector3 dragPosition;
void OnMouseDrag()
{
dragPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
dragPosition = Camera.main.ScreenToWorldPoint(dragPosition);
dragPosition.z = 0.0f; // assuming 2D game
}
void Update() {
transform.position = dragPosition;
}
}
Answer by SubatomicHero · May 14, 2013 at 07:47 AM
I think the order of your code is illogical. Think about what you need to do step by step. However as you're new to Unity I think the function should look like this:
void OnMouseDrag()
{
if (Input.GetMouseButtonDown(0))
{
// you have a vector 3 position
v3Prev = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
}
void Update()
{
// Do your gameobject movements here
transform.position = v3Prev;
}
Assuming this script is attached to your object of course. This is untested as I am at work. Hope this helps
Your answer
![](https://koobas.hobune.stream/wayback/20220613102202im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How will i drag my object with out object disturb? 0 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Coding A Tornado Particle Effect 0 Answers
I need help with scripting 0 Answers