首页 > 解决方案 > 当鼠标仅在一个方向拖动以及鼠标释放捕捉到网格时如何平滑移动游戏对象(Unity)

问题描述

我正在做一个小游戏。到目前为止,我设法在 x 或 Y 方向上移动块。现在我只是将块捕捉到网格。我想让它平滑地跟随鼠标,当我释放对象时应该捕捉到附近的网格。我不是计算屏幕和世界位置的上帝。希望有经验的人指导一下。这些是Quard,而不是UI 元素。

这是内部更新

 if (dragging) { //if dragging shoot raycast
   if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition),
       out hit, Mathf.Infinity, blockLayer)) {
     Debug.Log("isnide dragging");
     //Parent GameObject
     //initialize empty obj and make it parent
     tempParentObj = ParentGameObjectWithNewObject();

     //calculation for movement
     if (previousPart != null) {

       Vector3 previousPos = hit.point;
       Vector3 worldPos = hit.point;
       worldPos.z = adjustedHeight;

       worldPos.x = Mathf.Round(hit.point.x);

       worldPos.y = Mathf.Round(hit.point.y);

       //Code to restrict block to change its X and y pos at the same time.
       if (worldPos.y != previousPart.transform.position.y && worldPos.x != previousPart.transform.position.x) {
         Debug.Log("returning");
         return;
       }
       //parent object of block move
       tempParentObj.transform.position = worldPos;

     }
   }

进展至今

在此处输入图像描述

我想要达到的目标

在此处输入图像描述

谢谢您阅读此篇。任何参考都会有所帮助。谢谢你。

标签: pointersunity3dmouseeventgame-centerraycasting

解决方案


推荐阅读