我有一个包含描述轨迹路径的 SCNVector3 顶点的数组。我想画出它的路径。
- (SCNNode *)lineNodeFromVertices:(SCNVector3 *)vertices count:(NSUInteger)count
{
NSInteger numberOfVertices = (count - 1) * 2;
int *verticesSequence = calloc(numberOfVertices, sizeof(int));
for (int index = 0; index < count; index ++)
{
if (index > 0 && index < count - 1)
{
verticesSequence[index * 2 - 1] = index;
verticesSequence[index * 2] = index;
}
else if (index == 0)
{
verticesSequence[0] = index;
}
else if (index == count - 1)
{
verticesSequence[index * 2 - 1] = index;
}
}
NSData *sequenceData = [NSData dataWithBytes:verticesSequence
length:sizeof(verticesSequence)];
free(verticesSequence);
SCNGeometryElement *element = [SCNGeometryElement geometryElementWithData:sequenceData primitiveType:SCNGeometryPrimitiveTypeLine
primitiveCount:(count - 1)
bytesPerIndex:sizeof(int)];
SCNGeometrySource *source = [SCNGeometrySource geometrySourceWithVertices:vertices
count:count];
SCNGeometry *line = [SCNGeometry geometryWithSources:@[source]
elements:@[element]];
return [SCNNode nodeWithGeometry:line];
}
当我传递动态创建的数组作为创建 SCNGeometryElement 的参数时,它不起作用。
但是当我传递具有预定义元素数量的数组时它工作正常。 像这样的东西:
// Sample data
SCNVector3 vertices[] =
{
SCNVector3Make(1.0, 1.5, 0.5),
SCNVector3Make(0.8, 1.0, 0.2),
SCNVector3Make(0.4, 2.0, 1.2),
SCNVector3Make(0.0, 2.5, 2.7),
SCNVector3Make(-0.2, 2.0, 4.0),
SCNVector3Make(-0.4, 0.5, 5.0),
SCNVector3Make(-0.3, 3.0, 3.0)
};
int count = sizeof(vertices) / sizeof(vertices[0]);
// Array with predefined vertices sequence
int verticesSequence[] =
{
0, 1,
1, 2,
2, 3,
3, 4,
4, 5,
5, 6
};
NSData *sequenceData = [NSData dataWithBytes:verticesSequence
length:sizeof(verticesSequence)];
SCNGeometryElement *element = [SCNGeometryElement geometryElementWithData:sequenceData primitiveType:SCNGeometryPrimitiveTypeLine
primitiveCount:(count - 1)
bytesPerIndex:sizeof(int)];
SCNGeometrySource *source = [SCNGeometrySource geometrySourceWithVertices:vertices
count:count];
SCNGeometry *line = [SCNGeometry geometryWithSources:@[source]
elements:@[element]];
[self.rootSceneNode addChildNode:[SCNNode nodeWithGeometry:line]];
是否存在其他方法来创建具有非预定义顶点数的线节点?
最佳答案
您面临的问题是,int 指针的大小是指针本身的大小,而不是它指向的内存。
所以动态分配内存时,大小(我跑的时候)是8
int *verticesSequence = calloc(numberOfVertices, sizeof(int));
sizeof(verticesSequence); // 8
与当时预定义的数组相比,它的大小为 48(当我运行它时)
int verticesSequence[] = { 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6 };
sizeof(verticesSequence); // 48
这会导致一个问题,即当您创建 NSData 对象时,您只能获取它的前 8 个字节。
相反,您想要的是分配内存的大小 (sizeof(int) * numberOfVertices
)
sizeof(int)*numberOfVertices; // 48
我给了a similar explanation for Swift in this answer .
因此,更改 NSData 创建以使用它
NSData *sequenceData = [NSData dataWithBytes:verticesSequence
length:sizeof(int)*numberOfVertices];
关于ios - 如何创建具有非预定义顶点数的 SCNode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30487324/