首页 > 解决方案 > Unity 策略游戏的拖放仅适用于 2 个轴

问题描述

我目前正在开发一款带有拖放控件的游戏。问题是拖放仅适用于 2 个轴。目标是GameObject在地图上向各个方向拖动。GameObject只需要稍微抬起(在 y 轴上)。

如何GameObject在所有三个轴上移动?

这是代码:

public class DragDrop : MonoBehaviour
{
    public bool isDragging;

    public Vector3 mouse_offset;
    private float mouse_z_coord;
    private float mouse_y_coord;
    private float mouse_y_offset = 1;

    void Start()
    {
        rend = GetComponent<MeshRenderer>();
        Debug.Log(rend);
        defaultColor = Color.yellow;
        mouseOverColor = Color.blue;
    }

    private void OnMouseDown() 
    {
        transform.position += new Vector3(0,1,0);
        mouse_z_coord = Camera.main.WorldToScreenPoint(transform.position).z;
        mouse_y_coord = Mathf.Clamp(Camera.main.WorldToScreenPoint(transform.position).y, 0, mouse_y_offset);
        
        mouse_offset = transform.position - GetMouseAsWorldPoint();
        isDragging = true;
    }

    private Vector3 GetMouseAsWorldPoint() 
    {
        // Screenpoint coordinates of the mouse.
        Vector3 mousePoint = Input.mousePosition;

        // z coordinate of dragged gameobject.
        mousePoint.z = mouse_z_coord;

        mousePoint.y = mouse_y_coord;

        // Convert to world space.
        return Camera.main.ScreenToWorldPoint(mousePoint);
    }

    private void onMouseDrag() 
    {
        transform.position = GetMouseAsWorldPoint() + mouse_offset;
    }

    private void OnMouseUp() 
    {
        // Remove hardcode value.
        isDragging = false;
    }

    private void Update() 
    {
        if (isDragging) 
        {
            transform.position = GetMouseAsWorldPoint() + mouse_offset;
        }
    }
}

已经试过了->

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit)) 
        {
            transform.position = hit.point;
            transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
        }

这应该将对象放置在来自我的鼠标光标的射线的位置,但它不起作用。物体被沿着光线拖拽到相机中。

这是 UnityScene 的下载链接: https ://easyupload.io/wu76sj

标签: c#unity3ddrag-and-drop

解决方案


推荐阅读