- Home /
Game object moving in opposite direction instead of same direction while dragging it
This is the code for moving an object while dragging in the screen. Now the problem is that this moves the game object to the opposite direction when I drag on the screen. For example, if I drag from right to left on the screen, the game object moves from left to right. I want the game object to be moved from right to left only. How can this be done in this code? Can someone please help me?
#if UNITY_EDITOR
if (Input.GetMouseButtonDown(0))
{
screenPos = Camera.main.WorldToScreenPoint(this.transform.localPosition);
offset = this.transform.localPosition - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPos.z));
}
if (Input.GetMouseButton(0))
{
currentScreenPos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPos.z);
CurrentPos = Camera.main.ScreenToWorldPoint(currentScreenPos) + offset;
this.transform.localPosition = new Vector2(CurrentPos.x*movementFactor, this.transform.localPosition.y);
}
#endif
If I had to guess, my guess would be that the GameObject you're trying to move is rotated 180 degrees around Y or Z axis. This would cause the transform.localPosition update to move it opposite the way you expect. If you switch all instances of localPosition
with position
, I think you'll have better results.
If the object is not rotated, then this isn't the cause. It might be better to store a 'lastScreenPos' variable and just compare that to 'currentScreenPos' each frame, updating transform.position based on the difference and then setting 'lastScreenPos' to 'currentScreenPos' for the next frame.