我只是想用鼠标拖动来移动对象。对象是父对象的子对象。这就是代码中使用 localPosition 的原因。Vector3 startPos;Vector3 dist;void OnMouseDown(){ startPos = Camera.main.WorldToScreenPoint(transform.localPosition); dist = transform.localPosition - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, startPos.z));}void OnMouseDrag(){ Vector3 lastPos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, startPos.z); transform.localPosition = Camera.main.ScreenToWorldPoint(lastPos) + dist;}预期在 x&z 轴上移动对象,但在 x&y 上移动。
1 回答
墨色风雨
TA贡献1853条经验 获得超6个赞
您需要翻转它,以便使用 Input.mousePosition.y 作为 z 轴,使用 startPos 作为 y 轴。这应该有效:
public class MovementController : MonoBehaviour
{
private const float planeY = 0f;
Plane plane = new Plane(Vector3.up, Vector3.up * planeY); // ground plane
void OnMouseDrag()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float distance; // the distance from the ray origin to the ray intersection of the plane
if(plane.Raycast(ray, out distance))
{
transform.position = ray.GetPoint(distance); // distance along the ray
}
}
}
- 1 回答
- 0 关注
- 84 浏览
添加回答
举报
0/150
提交
取消