19 World coordinate transformation under different cameras in the deep pit

Problem Description

In order to unify the position of some objects, we often use setWorldPosition to directly set the position of an object.

But if we want to set the position of some UI components to the position of the corresponding game object, there will often be some problems.

For example, here, I have a problem

Since the height of the ui camera is different from that of the object camera, if their components are at the same position, they will appear to be in different positions

For example, I use this code here to make a ui component in the position of a certain object

/**呼唤单位选定窗口 */
  CallUnitSelectWin(unitCom: BasicUnit) {
    console.log('监察一下')
    let unit = unitCom.node;
   let pos = unit.getWorldPosition()
    this.node.setWorldPosition(pos)
    
  }

Then something like this happens

This translucent white is a square block, and you can see that his position conflicts with the position of the turret I want to place.

At this time, their world coordinates are actually the same, but their positions on the screen are actually different.

The red and blue squares are what I used for the confirm and cancel buttons, they haven't been placed yet.

How to solve

We need to know where certain objects should be projected to be suitable. After all, world coordinates just provide the location, but the camera is what makes them appear.

So we need to add some coordinate conversion code to convert.

 /**呼唤单位选定窗口 */
  CallUnitSelectWin(unitCom: BasicUnit) {
    
    let unit = unitCom.node;
    //获取物体的实际世界坐标
   let pos = unit.getWorldPosition()
   //坐标转换,获取正确的ui位置
    pos = GameManager.getInstance().WorldPosToUICameraWorldPos(pos);
    //把ui位置上升,防止ui挡住物体
    pos.y+=150
    //设置位置
    this.node.setWorldPosition(pos)
    
    
  }
  /**将普通世界坐标转换为基于ui摄像机的世界坐标 */
  WorldPosToUICameraWorldPos(pos: Vec3):Vec3 {
  //将物体坐标转换成屏幕坐标,基于物体摄像机
    let pos2 = new Vec3();
    this.GetMainCamera().camera.worldToScreen(pos2, pos);
    //将屏幕坐标转换成ui坐标,基于ui摄像机
    let pos3= new Vec3();;
    this.GetUICamera().camera.screenToWorld(pos3, pos2);
    return pos3;
  }

process result

The ui is right above to complete the requirements

Clicking on other locations can also work normally

Guess you like

Origin blog.csdn.net/Yourset/article/details/128939777