gpt4 book ai didi

ios - iOS 上 Swift 中的自定义 SceneKit 几何体不起作用,但等效的 Objective C 代码可以

转载 作者:IT王子 更新时间:2023-10-29 05:30:04 24 4
gpt4 key购买 nike

我很想采用新的 Swift 语言,因为这似乎是 Apple 开发的前进方向。 iOS 8 中新的 SceneKit 支持给我留下了深刻的印象。我想在运行时以编程方式创建自定义几何图形,但我正在努力让 Swift 代码工作。然而,Objective C 中的等效代码工作正常。

这可能是一个错误,或者是我做错了什么。

我只是想创建并渲染一个三角形。为简单起见,此时我将忽略法线和纹理等。所以我只希望看到一个黑色三角形。

Swift 代码(不工作)

var verts = [SCNVector3(x: 0,y: 0,z: 0),SCNVector3(x: 1,y: 0,z: 0),SCNVector3(x: 0,y: 1,z: 0)]

let src = SCNGeometrySource(vertices: &verts, count: 3)
let indexes:Int[]=[0,1,2]
let dat = NSData(bytes: indexes, length: sizeofValue(indexes))
let ele = SCNGeometryElement(data:dat, primitiveType: .Triangles, primitiveCount: 1, bytesPerIndex: sizeof(Int))
let geo = SCNGeometry(sources: [src], elements: [ele])

let nd = SCNNode(geometry: geo)
scene.rootNode.addChildNode(nd)

Objective-C 代码(确实有效)

SCNVector3 verts[] = { SCNVector3Make(0, 0, 0), SCNVector3Make(1, 0, 0), SCNVector3Make(0, 1, 0) };
SCNGeometrySource *src = [SCNGeometrySource geometrySourceWithVertices:verts count:3];

int indexes[] = { 0, 1, 2 };
NSData *datIndexes = [NSData dataWithBytes:indexes length:sizeof(indexes)];
SCNGeometryElement *ele = [SCNGeometryElement geometryElementWithData:datIndexes primitiveType:SCNGeometryPrimitiveTypeTriangles primitiveCount:1 bytesPerIndex:sizeof(int)];
SCNGeometry *geo = [SCNGeometry geometryWithSources:@[src] elements:@[ele]];

SCNNode *nd = [SCNNode nodeWithGeometry:geo];
d
[scene.rootNode addChildNode:nd];

如有任何指点,我们将不胜感激。

最佳答案

好吧,这两段代码不能完全相互转换。 C 中的 int 与 Swift 中的 Int 不同。它实际上在 Swift 中称为 CInt:

/// The C 'int' type.
typealias CInt = Int32

如果您将这两个事件更改为使用 CInt,您之前收到的错误消息就会消失(至少对我来说是在 OS X Playground 中。但是,它仍然不会呈现任何内容我。

我不认为 sizeofValue 用于返回数组的大小。在我看来它正在返回指针的大小:

let indexes: CInt[] = [0, 1, 2]
sizeofValue(indexes) // is 8
sizeof(CInt) // is 4
sizeof(CInt) * countElements(indexes) // is 12

// compare to other CInt[]
let empty: CInt[] = []
let large: CInt[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

sizeofValue(indexes) // is 8 (your array of indices again)
sizeofValue(empty) // is 8
sizeofValue(large) // is 8

因此,对我来说,以下代码有效(我将参数放在不同的行上,以便更容易指出我的更改):

let src = SCNGeometrySource(vertices: &verts, count: 3)
let indexes: CInt[] = [0, 1, 2] // Changed to CInt

let dat = NSData(
bytes: indexes,
length: sizeof(CInt) * countElements(indexes) // Changed to size of CInt * count
)
let ele = SCNGeometryElement(
data: dat,
primitiveType: .Triangles,
primitiveCount: 1,
bytesPerIndex: sizeof(CInt) // Changed to CInt
)
let geo = SCNGeometry(sources: [src], elements: [ele])

let nd = SCNNode(geometry: geo)
scene.rootNode.addChildNode(nd)

结果是:

enter image description here

关于ios - iOS 上 Swift 中的自定义 SceneKit 几何体不起作用,但等效的 Objective C 代码可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24493273/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com