旧人旧梦旧心情 2023-08-14 16:52 采纳率: 0%
浏览 5

cesium模型平移问题


var xNew=0;
var yNew=0;
var zNew=0;
var zNewz=0;
var xNewx=0;
var yNewy=0;
var xcor=Cesium.Color.ORANGE;
var ycor=Cesium.Color.GREEN;
var zcor=Cesium.Color.BLUE;
var pingmuy =0;
var cameraHeight=0;
var differencez=0;
// var primitives = new Cesium.PrimitiveCollection();
// var  primitivecol=null;
var handler=null;
var tx = 0;
var ty = 0;
var tz = 0;
var rx = 0;
var ry = 0;
var rz = 0;
var scale = 1;
function move(i) { 
  var arrPrimity=addzuobiaoxi();
  var tileset=arrPrimity[0];
  var boundingSphere = tileset.boundingSphere;
  var cartographic1 = Cesium.Cartographic.fromCartesian(boundingSphere.center);
     // 为 x 轴添加鼠标点击事件
     handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
     debugger
     handler.setInputAction(function (e) {
      // 获取第一个Primitive实例
      const primitive=viewer.scene.primitives._primitives[i]._primitives[1];
      debugger
      const primitivecircle=viewer.scene.primitives._primitives[i]._primitives[0];
      debugger
      //将笛卡尔坐标转化为弧度坐标
         let pick = viewer.scene.pick(e.position);
        if(pick && pick.id){
          if(pick.id == "xid"){
            primitive.getGeometryInstanceAttributes("xid").color=Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromRandom(Cesium.Color.RED));
            primitive.getGeometryInstanceAttributes("yid").color=Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromRandom(ycor));
            primitive.getGeometryInstanceAttributes("zid").color=Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromRandom(zcor));
            xFlag = !xFlag
            yFlag = false;
            zFlag = false;
          }
          if(pick.id == "yid"){
            primitive.getGeometryInstanceAttributes("xid").color=Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromRandom(xcor));
            primitive.getGeometryInstanceAttributes("yid").color=Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromRandom(Cesium.Color.RED));
            primitive.getGeometryInstanceAttributes("zid").color=Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromRandom(zcor));
            yFlag = !yFlag;
            xFlag = false;
            zFlag = false;
          }
          if(pick.id == "zid"){
            primitive.getGeometryInstanceAttributes("xid").color=Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromRandom(xcor));
            primitive.getGeometryInstanceAttributes("yid").color=Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromRandom(ycor));
            primitive.getGeometryInstanceAttributes("zid").color=Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromRandom(Cesium.Color.RED));
  
            zFlag = !zFlag;
            xFlag = false;
            yFlag = false; 
          }
          if(pick.id == "circleid"){
            primitive.getGeometryInstanceAttributes("xid").color=Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromRandom(Cesium.Color.RED));
            primitive.getGeometryInstanceAttributes("yid").color=Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromRandom(Cesium.Color.RED));
            primitive.getGeometryInstanceAttributes("zid").color=Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromRandom(Cesium.Color.RED));
            yFlag = !yFlag;
            xFlag = !xFlag;
            zFlag = !zFlag;
             // 点击了"circleid",获取其坐标
          }
            // const primitive=viewer.scene.primitives;
            var pingmupostition=e.position;
            startMoveInputAction(handler,tileset,primitive,primitivecircle,cartographic1,pingmupostition); 
        }else{
          xFlag = false;
          yFlag = false;
          zFlag = false;
          handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        }
        if(!xFlag){
          primitive.getGeometryInstanceAttributes("xid").color=Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromRandom(xcor));
        }
        if(!yFlag){
          primitive.getGeometryInstanceAttributes("yid").color=Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromRandom(ycor));
        }
        if(!zFlag){
          primitive.getGeometryInstanceAttributes("zid").color=Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromRandom(zcor));
        }
     }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  }
  function startMoveInputAction(handler,tileset,primitive,primitivecircle,cartographic1){
    handler.setInputAction(function (moveEvent) {
      var movePosition = this.viewer.scene.globe.pick(this.viewer.camera.getPickRay(moveEvent.endPosition), this.viewer.scene);
      //因为当前情况下y轴是向下为正数  所以应该获取的时候做一下操作 需要用幕布全高度减去当前鼠标的值才是所需要增加的值
      //幕布的值减去 
      // 获取相机的位置
      var cameraPosition = viewer.camera.positionCartographic;
      // 获取相机的高度
      cameraHeight = cameraPosition.height;
      if (!movePosition) {
          return false;
      }
      var cartographic = Cesium.Cartographic.fromCartesian(movePosition);//迪卡尔3
      var differencex = cartographic.longitude-cartographic1.longitude;
      var differencey = cartographic.latitude-cartographic1.latitude;
 // 将世界坐标坐标转换为屏幕坐标
      // 获取屏幕的宽度和高度
      const screenWidth = viewer.canvas.clientWidth;
      const screenHeight = viewer.canvas.clientHeight;
      var boundingSphere = tileset.boundingSphere; // 包围盒

      var cartographicTileset = Cesium.Cartographic.fromCartesian(boundingSphere.center); // 迪卡尔3
      
      // 获取世界坐标点
      const worldPosition = Cesium.Cartesian3.fromRadians(cartographicTileset.longitude, cartographicTileset.latitude, cartographicTileset.height);
      
      // 将世界坐标点转换为屏幕坐标
      const screenPosition = new Cesium.Cartesian2();
      viewer.scene.cartesianToCanvasCoordinates(worldPosition, screenPosition);
      // 获取屏幕坐标
      const screenX = screenPosition.x;
      const screenY = screenPosition.y;
      // debugger   
      if(xFlag){
      moveTileSetByRadians1(tileset,differencex,yNew,zNewz,primitive,primitivecircle)
      }
      if(yFlag){
       moveTileSetByRadians1(tileset,xNew,differencey,zNewz,primitive,primitivecircle)
      }
      if(zFlag){
        differencez=screenPosition.y-moveEvent.endPosition.y;
        console.log(differencez)
        moveTileSetByRadians1(tileset,xNew,yNew,differencez,primitive,primitivecircle)
      }
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  }
//通过弧度移动
function moveTileSetByRadians1(tileset,longitude,latitude,altitude,primitive,primitivecircle) {
    var boundingSphere = tileset.boundingSphere;//包围盒
    var cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);//迪卡尔3
    var surface =Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude,cartographic.height);//转成弧度
    //在现在的位置基础上,添加移动的量
    var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude+longitude, cartographic.latitude+latitude,cartographic.height+altitude+zNew);
    xNew=longitude;
    yNew=latitude;
    zNewz=altitude-zNewz;
    zNew=altitude+zNew;
    xNewx=longitude+xNew;
    yNewy=altitude+yNew;
    //移动
     var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
    tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
    primitive.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
    primitivecircle.modelMatrix=Cesium.Matrix4.fromTranslation(translation);
    // var transformedCenter = Cesium.Matrix4.multiplyByPoint(tileset.modelMatrix, originalBoundingSphere.center, new Cesium.Cartesian3());
}
function addzuobiaoxi(){
  var arrPrimity = viewer.scene.primitives._primitives.filter(
    (t) => t.primityFlag && t.primityFlag.startsWith('draft')
  );
  var boundingSphere = arrPrimity[0].boundingSphere;
  // 创建一个坐标轴
  var transform = Cesium.Transforms.eastNorthUpToFixedFrame(boundingSphere.center);
 // 创建带箭头的线段
 const arrowMaterial = new Cesium.PolylineArrowMaterialProperty();
  // 创建 X 轴箭头
  var x = new Cesium.GeometryInstance({
    geometry: new Cesium.PolylineGeometry({
      positions: [Cesium.Cartesian3.ZERO, Cesium.Cartesian3.UNIT_X],
      width: 5,
      vertexFormat: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
      arcType: Cesium.ArcType.NONE,
      depthFailMaterial: new Cesium.PolylineDashMaterialProperty({
      dashLength: 16,
      dashPattern: 255,
      with:5
      })
    }),
    id: "xid",
    modelMatrix: Cesium.Matrix4.multiplyByUniformScale(
      transform,
      400,
      new Cesium.Matrix4()
    ),
    attributes: {
      color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.ORANGE),
    },
    // 设置材质属性
    appearance: new Cesium.PolylineMaterialAppearance({
      material: arrowMaterial,
      // 设置深度测试失败时的材质,将几何体实例的颜色设置为虚线颜色
      depthFailMaterial: new Cesium.PolylineDashMaterialProperty({
        color: Cesium.Color.fromCssColorString('#ff0000'),
        dashLength: 16.0,
        dashPattern: 255.0,
      })
    }),
  });
  // 创建 Y 轴箭头
  const y = new Cesium.GeometryInstance({
    geometry: new Cesium.PolylineGeometry({
      positions: [Cesium.Cartesian3.ZERO, Cesium.Cartesian3.UNIT_Y],
      width: 5,
      vertexFormat: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
      arcType: Cesium.ArcType.NONE,
      depthFailMaterial: new Cesium.PolylineDashMaterialProperty({
        color: Cesium.Color.GREEN,
        dashLength: 16,
        dashPattern: 255,
        with:5
      }),
    }),
    id: "yid",
    modelMatrix: Cesium.Matrix4.multiplyByUniformScale(
      transform,
      400,
      new Cesium.Matrix4()
    ),
    attributes: {
      color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.GREEN),
    },
    // 设置材质属性
    appearance: new Cesium.PolylineMaterialAppearance({
      material: arrowMaterial,
    }),
  });

  // 创建 Z 轴箭头
  const z = new Cesium.GeometryInstance({
    geometry: new Cesium.PolylineGeometry({
      positions: [Cesium.Cartesian3.ZERO, Cesium.Cartesian3.UNIT_Z],
      width: 5,
      vertexFormat: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
      arcType: Cesium.ArcType.NONE,
      depthFailMaterial: new Cesium.PolylineDashMaterialProperty({
        color: Cesium.Color.BLUE,
        dashLength: 16,
        dashPattern: 255,
        with:5
      }),
    }),
    id: "zid",
    modelMatrix: Cesium.Matrix4.multiplyByUniformScale(
      transform,
      400,
      new Cesium.Matrix4()
    ),
    attributes: {
      color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.BLUE),
    },
    // 设置材质属性
    appearance: new Cesium.PolylineMaterialAppearance({
      material: arrowMaterial,
    }),
     // 将 classificationType 属性设置为 CESIUM_3D_TILE
  classificationType: Cesium.ClassificationType.CESIUM_3D_TILE,
  })
  // Create a circle.
  const circle = new Cesium.CircleGeometry({
    center: boundingSphere.center,
    radius: 100,
    height:boundingSphere.center.height,
  });
  const circleInstance = new Cesium.GeometryInstance({
    geometry: circle,
    attributes: {
      color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.YELLOW),
    },
    appearance: new Cesium.EllipsoidSurfaceAppearance({
      material: new Cesium.Material({
        fabric: {
          type: 'Color',
          uniforms: {
            color: Cesium.Color.YELLOW,
          },
        },
      }),
      depthTestAgainstTerrain: false, // 设置深度测试
      classificationType:Cesium.ClassificationType.CESIUM_3D_TILE
    }),
    id: "circleid",
  });
 primitives = new Cesium.PrimitiveCollection(); 

//  moveTileSetByRadians1(xNew,yNew,zNew)

primitives.add(new Cesium.Primitive({
  primityFlag: 'zb',
  releaseGeometryInstances: false,
  geometryInstances: [circleInstance],
  appearance: new Cesium.PolylineColorAppearance({translucent:false,closed:true}),
  asynchronous:false
}));
 primitives.add(new Cesium.Primitive({
  primityFlag: 'zb',
  releaseGeometryInstances:false,
  geometryInstances: [x,y,z],
  appearance: new Cesium.PolylineColorAppearance({translucent:false,closed:true}),
  asynchronous:false
}))
 primitivecol=viewer.scene.primitives.add(primitives);
 return arrPrimity;
}

//删除坐标系
function removezbx(){
    primitives.removeAll(primitive => primitive.id && primitive.id.startsWith("zb"));
    // primitives.destroy(primitive => primitive.id && primitive.id.startsWith("zb"));
    handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
}

代码存在问题 移动后删除坐标系再添加进来再次移动模型会回弹点击坐标 并且坐标系也有bug 如何实现删除坐标系再次添加处于移动后的位置

  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2023-08-14 19:58
    关注

    【以下回答由 GPT 生成】

    该代码片段的优化点主要有以下几个方面:

    1. 变量命名:变量名称要符合规范和语义,避免使用不具有明确含义的名称,比如xNew、yNew、zNew等。可以根据变量使用的上下文给出更有描述性的名称。

    2. 变量声明和初始化:尽量将变量的声明和初始化放在使用的位置附近,并且最小化变量的作用域。代码片段中有很多未使用的变量和赋初值为0的变量,这些可以删除或者移到具体使用位置。

    3. 代码格式化:代码格式要统一,使用一定的缩进和换行来提高可读性。

    4. 错误处理:代码中没有对可能出现的异常情况进行处理,需要添加错误处理机制,比如try-catch语句来捕获异常。

    5. 冗余代码:代码中有一些不必要的注释和调试语句可以删除。

    下面是对代码进行的优化示例:

    function move(primitiveIndex) { 
      const primitive = viewer.scene.primitives._primitives[primitiveIndex]._primitives[1];
      const primitivecircle = viewer.scene.primitives._primitives[primitiveIndex]._primitives[0];
    
      const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    
      handler.setInputAction(function (e) {
        try {
          const pick = viewer.scene.pick(e.position);
    
          // 进一步操作
          // ...
        } catch (error) {
          console.error(error);
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }
    

    注意:由于代码片段提供的信息有限,以上示例只对给出的代码进行了部分优化,并不能保证完全解决问题。请根据具体情况对代码进行优化。



    【相关推荐】



    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论

报告相同问题?

问题事件

  • 创建了问题 8月14日

悬赏问题

  • ¥15 依据报错在原代吗格式的基础上解决问题
  • ¥15 在虚拟机中安装flash code
  • ¥15 单片机stm32f10x编写光敏电阻调节3.3伏大功率灯亮度(光强越大灯越暗,白天正常光强灯不亮,使用ADC,PWM等模块)望各位找一下错误或者提供一个可实现功能的代码
  • ¥20 verilog状态机方法流水灯
  • ¥15 pandas代码实现不了意图
  • ¥15 GD32H7 从存储器到外设SPI传输数据无法重复启用DMA
  • ¥25 LT码在高斯信道下的误码率仿真
  • ¥45 渲染完成之后将物体的材质贴图改变,自动化进行这个操作
  • ¥15 yolov5目标检测并显示目标出现的时间或视频帧
  • ¥15 电视版的优酷可以设置电影连续播放吗?