c# - 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
解决方案
推荐阅读
- ios - 带有部分的快速表格视图无法使用搜索栏
- pip - 如何在 Airflow 中安装软件包?
- julia - 如何更改Julia中矩阵下三角的值并转换为上三角?
- image-processing - Spark 如何使用图像格式读取我的图像?
- vb.net - 如何修复缺少 CategoryName 错误消息?
- swift - 如何使用 Cloud Firestore 中的地理点设置 tableview 以放置离我当前位置最近的商店?
- sql-server - 通过 SQL Server 2016 中的 SSMS 识别 SSIS 中的数据源
- python - 为什么我的 for 循环没有遍历完整的熊猫列表
- rust - 如何从特征实现中返回 HashMap 键的迭代器?
- sql-server - 如何使用 Shiny App 中的存储过程提取数据?