Reputation: 363
Okay, so I am preparing a game of Ludo with only two players having 4 pawns each. I am using a dice which is when clicked will rotate randomly giving an output.
While dragging the pawn the y axis is also decreasing. So when the blue pawn is dragged towards red one it will go under the board(which should not happen.) How to figure it out?
Here's my C# code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
RequireComponent(typeof(MeshCollider))]
public class DragPawn : MonoBehaviour
{
private Vector3 screenPoint;
private Vector3 offset;
void OnMouseDown()
{
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
}
Here's the image with the problem
Upvotes: 0
Views: 654
Reputation: 428
It looks like your board is using a vertical axis of Z and an horizontal axis of X. But i think your code is using X and Y.
Regardless, i think your offset variable should use '0' in the axis in which it should be locked, since you are adding it to the transform, if it is non-zero you will be modifying that axis.
Edit:
Just think about it, you want to add to only 2 dimensions of a 3 dimensional structure. If your object is at, say, [15, 10, 8] and you want to move it up 10 in the X direction you have to add to the X dimension only. ([10, 0, 0]
)
[15, 10, 8] + [10, 0, 0] = [25, 10, 8]
I suspect your offset variable looks something like [10, 0, 2]
or something, so when you add it, you're adding to the Z dimension when you don't intend to.
ie: [15, 10, 8] + [10, 0, 2] = [25, 10, 10]
Upvotes: 1