思路&步骤
大致思想就是利用viewport场景中,相机的方向与模型所在点确定模型的移动平面。再将鼠标在屏幕上的2d坐标转换成viewport中的3d坐标,确定模型新的位置。
- 鼠标按下时,先拿到模型visual
- 鼠标移动时,将鼠标的二维坐标转换成viewport场景中的射线
- 得到射线与移动平面的交点,并以该交点作为模型的新位置
- 使用Transform更新模型位置
代码实现
前台:
1 <Window 2 x:Class="MouseDrag.MainWindow" 3 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 4 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 5 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 6 xmlns:helix="http://helix-toolkit.org/wpf" 7 xmlns:local="clr-namespace:MouseDrag" 8 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 9 Title="MainWindow" 10 Width="800" 11 Height="450" 12 mc:Ignorable="d"> 13 <Grid> 14 <helix:HelixViewport3D 15 x:Name="view" 16 Background="LightGray" 17 Camera="{helix:PerspectiveCamera 43.11, 18 -74.67, 19 49.78}" 20 MouseDown="view_MouseDown" 21 MouseMove="view_MouseMove" 22 ShowCameraInfo="True" 23 ShowCoordinateSystem="True"> 24 <helix:GridLinesVisual3D /> 25 <helix:DefaultLights /> 26 <helix:CubeVisual3D x:Name="cube" SideLength="10" /> 27 </helix:HelixViewport3D> 28 </Grid> 29 </Window>前台
后台:
1 using HelixToolkit.Wpf; 2 using System.Windows; 3 using System.Windows.Input; 4 using System.Windows.Media.Media3D; 5 6 namespace MouseDrag 7 { 8 /// <summary> 9 /// MainWindow.xaml 的交互逻辑 10 /// </summary> 11 public partial class MainWindow : Window 12 { 13 CubeVisual3D selectCube = new CubeVisual3D(); 14 15 public MainWindow() 16 { 17 InitializeComponent(); 18 cube2.Transform = new TranslateTransform3D(20, 0, 0); 19 } 20 21 private void view_MouseDown(object sender, MouseButtonEventArgs e) 22 { 23 Visual3D visual = view.FindNearestVisual(e.GetPosition(view)); 24 if(visual != null && visual is CubeVisual3D) 25 { 26 selectCube = visual as CubeVisual3D;//捕获按下的visual 27 } 28 } 29 private void view_MouseMove(object sender, MouseEventArgs e) 30 { 31 if (e.LeftButton == MouseButtonState.Pressed) 32 { 33 Matrix3D mat = cube.Transform.Value;//模型的变换矩阵 34 Vector3D lookdirction = view.Camera.LookDirection;//相机方向 35 Point3D dot = new Point3D(mat.OffsetX, mat.OffsetY, mat.OffsetZ);//模型位置 36 37 Ray3D ray = Viewport3DHelper.Point2DtoRay3D(view.Viewport, e.GetPosition(view));//射线类 38 var point = ray.PlaneIntersection(dot, lookdirction);//移动平面上的交点 39 40 mat.OffsetX = ((Point3D)point).X; 41 mat.OffsetY = ((Point3D)point).Y; 42 mat.OffsetZ = ((Point3D)point).Z; 43 44 Transform3D trans = new MatrixTransform3D(mat); 45 cube.Transform = trans; 46 } 47 } 48 } 49 }后台代码
效果
标签:mat,鼠标,模型,visual,helixtoolkit,Point3D,拖拽,view From: https://www.cnblogs.com/night-owl/p/16817733.html