I have been trying to move an object with my mouse but not been able to have to work. I want to have the block move per block. I can do this with the key buttons with “Input.GetKeyDown” function. But I have a problem with the mouse. Based on the image, the red block is on the board. I want the block to move with the mouse per block/space on the board. Is there a way to move the block per space with mouse? This game is not using a grid. It moves on a X axis and Z axis. For example, if the object moves on left or right, it should move one whole space with the mouse.
I think one way would be to cast a Ray from the camera into the scene, if it hits your checkboard get the position of the hit and round the x and z position of the hit point to the size of one grid unit, for example if your grid unit is 10 x 10 you can do:
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit)) {
if (hit.collider.name == "Floor") {
int positionX = Mathf.Round(hit.point.x / 10) * 10; //Where 10 is the grid size
int positionZ = Mathf.Round(hit.point.z / 10) * 10;
Vector3 newPosition = new Vector3(positionX, 0, positionZ);
}
}
Thanks, the code works.
I have a question. How do i prevent the player to move the mouse from moving diagonal. So if I move the object on the x-axis, then the z-axis is not possible or if i move on the z-axis then the x-axis would not be possible. Or if I move diagonal , then it should move on the x-axis.
You can store the staring position when the user clicks, then, when the user moves the mouse, you check the current position and compare it to the starting position; if the difference in x is bigger than the differente in z, ignore z, otherwise ignore x.
Hello,
I seem to have a problem in trying to prevent the mouse object from moving diagonally. Could you please provide a sample code to show the object could not move diagonally? I tried it before but seem to not to work.
