我正在用Xcode14.3在iOS 16.1上开发一个3D场景.我有一个绕原点在斜坡上轨道的矩形平面,我想使用GLKMatrix4MakeLookAt使该平面始终面向原点.

我正在使用下面的代码.当飞机旋转时,它确实是面向原点的,然而我也看到了这种不受欢迎的来回摇摆.请看附件中的视频,了解它的样子.

为什么它会这么摇摆?我如何才能在摆脱摇摆的同时,仍然让平面绕原点运行并始终面对它?谢谢.

enter image description here

代码:

// Get the lookat scene origin matrix for the rectangle
var lookAtSceneOriginGLKMatrix = GLKMatrix4Identity
var lookAtSceneOriginInverse = GLKMatrix4Identity
var rectangleModelMatrix = float4x4()
var lookAtSceneOriginMat = float4x4()

lookAtSceneOriginGLKMatrix = GLKMatrix4Multiply(lookAtSceneOriginGLKMatrix, GLKMatrix4MakeLookAt(self.currentSatX * self.appDelegate.getCurrentRectangle().getRenderHeight(), self.currentSatY * self.appDelegate.getCurrentRectangle().getRenderHeight(), self.currentSatZ * self.appDelegate.getCurrentRectangle().getRenderHeight(), 0, 0, 0, 0, 1, 0))
var isInvertible = true
lookAtSceneOriginInverse = GLKMatrix4Invert(lookAtSceneOriginGLKMatrix, &isInvertible)
lookAtSceneOriginMat = float4x4(convertToFloat4x4FromGLKMatrix: lookAtSceneOriginInverse)
rectangleModelMatrix = accumulatedRotationMatrix * lookAtSceneOriginMat * float4x4(scaleBy: 0.35)

// Draw the rectangular plane
scene.rectanglePlane?.draw(
    encoder: commandEncoder, modelMatrix: rectangleModelMatrix,
    projectionMatrix: projectionMatrix * viewMatrix
)

推荐答案

正如 comments 中提到的,上方向向量始终指向y轴的方向.它应该垂直于方向向量.

let x = self.currentSatX * self.appDelegate.getCurrentRectangle().getRenderHeight()
let y = self.currentSaty * self.appDelegate.getCurrentRectangle().getRenderHeight()
let z = self.currentSatZ * self.appDelegate.getCurrentRectangle().getRenderHeight()

let direction = GLKVector3Make(x, y, z) //vector from planes postion to origin

let yAx = GLKVector3Make(0, 1, 0) // y axis

let side = GLKVector3CrossProduct(direction, yAx) //perpendicular vector to direction

let up = GLKVector3CrossProduct(side, direction) //perpendicular vector to side
let normalizedUp = GLKVector3Normalize(up)

lookAtSceneOriginGLKMatrix = GLKMatrix4Multiply(lookAtSceneOriginGLKMatrix, GLKMatrix4MakeLookAt(x, y, z, 0, 0, 0, normalizedUp.x, normalizedUp.y, normalizedUp.z))

Ios相关问答推荐

iOS中的分段拾取器—手柄点击已 Select 的项目

如何在本地iOS没有插件的情况下处理平台线程?

Xcode 15模拟器用x86_64编译

如何在@AppStorage中存储字体?

_SKStoreProductParameterAdNetworkSourceIdentifier未定义符号

Apple Metal iOS 为什么 GLKMatrix4MakeLookAt 来回摇摆

iOS 16.4 更新后 Xcode 14.3 构建错误:找不到 libarclite_iphoneos.a,链接器命令失败

SwiftUI 菜单中的内联水平按钮

使用 JSONDecoder 解码的对象的打印输出有问题

在 SwiftUI 中重构提取到子视图的 GeometryReader 代码

`Task` 在内部调用异步函数时阻塞主线程

iOS,Swift 5,AppDelegate open url / .onOpenUrl - 如何找到调用我的自定义方案的调用应用程序

为什么我的应用在 Testflight 中没有下载 dSYM 按钮?

如何在 Swift 3 中根据 UIImage 的大小/比率调整 UIImageView 的大小?

滑动列表项以获取更多选项(Flutter)

UIView 和 initWithFrame 以及一个 NIB 文件.如何加载 NIB 文件?

iOS UITextView 或 UILabel 带有可点击的动作链接

是否可以将 Socket.io 与 AWS Lambda 一起使用?

用 NavigationViewController 快速呈现 ViewController

在 iOS 上没有显示数字键盘