unity 沿著軸(x,y,z)拖動物體
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//選擇軸向
public enum axisPostion
{
x_dir,
y_dir,
z_dir,
}
public class DrageThree : MonoBehaviour
{
public axisPostion myDirection;
public Transform target;//需要拖拽的目標
public bool isDrag;//表示當前是否可拖動
private Vector3 mousePos;
private Vector3 ScreenSpace, curScreenSpace, offset, CurPosition;
void Start()
{
}
void Update()
{
DragTarget();
}
public void DragTarget()
{
if (isDrag)
{
ScreenSpace = Camera.main.WorldToScreenPoint(target.position); //目標世界座標轉螢幕,獲取z值
curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, ScreenSpace.z);//當前滑鼠位置轉世界
offset = target.position - Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, ScreenSpace.z));//滑鼠上一幀的世界位置和目標點的位置差
CurPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset;//滑鼠當前位置+位置差
switch (myDirection)
{
case axisPostion.x_dir:
target.position = new Vector3(CurPosition.x, target.position.y, target.position.z);
break;
case axisPostion.y_dir:
target.position = new Vector3(target.position.x, CurPosition.y, target.position.z);
break;
case axisPostion.z_dir:
target.position = new Vector3(target.position.x, target.position.y, CurPosition.z);
break;
default:
break;
}
mousePos = Input.mousePosition;
}
}
private void OnMouseDown()
{
isDrag = true;
mousePos = Input.mousePosition;
}
private void OnMouseDrag()
{
isDrag = true;
}
private void OnMouseUp()
{
isDrag = false;
}
}