Мне нужна помощь в размещении цвета в тесте моего куба РубикаIOS

Программируем под IOS
Ответить Пред. темаСлед. тема
Anonymous
 Мне нужна помощь в размещении цвета в тесте моего куба Рубика

Сообщение Anonymous »

Я разрабатываю 3D -куб Rubik, используя Scenekit в Swift, и я сталкиваюсь с проблемой, когда цвета лиц куба не производят, как сплошные лица 3x3, как и ожидалось. Вместо каждой поверхности куба 3x3x3 (например, передняя поверхность зеленого цвета, левая поверхность в оранжевом и т. Д.). покрывая все лицо. Например, я вижу зеленый цвет (предназначенный для передней поверхности, +z) правильно на верхнем ряду, но он перемещается в нижний ряд или соседние лица вместо формирования сплошной зеленой 3x3. < /P>
Вот обзор моей настройки и проблемы: < /p>
  • Objective < /strong>: я хочу каждую лицо Рубик Куб (спереди, сзади, влево, справа, вверху, внизу), чтобы быть сплошным цветом для 9 кублетов, которые составляют это лицо (например, все кублеты с z = 1 должны быть окрашены в зеленую переднюю поверхность).
    < /li>
    текущее поведение < /strong>: цвета применяются частично или в фрагментированных узорах (например, ряд зеленого вверху, затем ряд Зеленый ниже, но не сплошное зеленое лицо 3x3). Это происходит для всех лиц (красный для +x, оранжевый для -x, белый для +y, желтый для -y, зеленый для +z, синий для -z).
  • подозреваемая проблема < /strong>: я подозреваю, что кублеты (Scnbox) могут быть повернуты, в результате чего материалы применяются к неправильным лицам или не в неправильной ориентации, но я был Невозможно подтвердить или исправить это.
Вот мой код:
cubescene:

Код: Выделить всё

import SwiftUI
import SceneKit

class CuboScene: SCNScene {
override init() {
super.init()
rootNode.eulerAngles = SCNVector3(0, 0, 0)  // Ensure rootNode is not rotated
rootNode.position = SCNVector3(0, 0, 0)  // Ensure rootNode is at the origin
rootNode.scale = SCNVector3(1, 1, 1)  // Ensure no unexpected scaling

//        let light = SCNLight()
//        light.type = .omni
//        light.intensity = 2000
//        let lightNode = SCNNode()
//        lightNode.light = light
//        lightNode.position = SCNVector3(x: 5, y: 5, z: 5)
//        rootNode.addChildNode(lightNode)

configureLights()
createRubikCube()
}

private func createRubikCube() {
let size: CGFloat = 0.8
let spacing: CGFloat = 1.05

for x in -1...1 {
for y in -1...1 {
for z in -1...1 {
let cubelet = SCNBox(width: size, height: size, length: size, chamferRadius: 0.0)  // No rounded edges
let cubeletNode = SCNNode(geometry: cubelet)
cubeletNode.position = SCNVector3(Float(x) * Float(spacing),
Float(y) * Float(spacing),
Float(z) * Float(spacing))
cubeletNode.eulerAngles = SCNVector3(0, 0, 0)  // Ensure no rotation
print("Cubelet at position: (\(Float(x) * Float(spacing)), \(Float(y) * Float(spacing)), \(Float(z) * Float(spacing)) with materials: \(getFaceMaterial(x: x, y: y, z: z).map { $0.diffuse.contents as? UIColor ?? .gray }) and eulerAngles: \(cubeletNode.eulerAngles), rotation: \(cubeletNode.rotation)")

cubelet.materials = getFaceMaterial(x: x, y: y, z: z)
rootNode.addChildNode(cubeletNode)
}
}
}
}

private func getFaceMaterial(x: Int, y: Int, z: Int) -> [SCNMaterial] {
let colors: [UIColor] = [
// Right face (+X): red if x = 1, gray for x = 0 or -1
(x == 1) ? .red : .gray,
// Left face (-X): orange if x = -1, gray for x = 0 or 1
(x == -1) ? .orange : .gray,
// Top face (+Y): white if y = 1, gray for y = 0 or -1
(y == 1) ? .white : .gray,
// Bottom face (-Y): yellow if y = -1, gray for y = 0 or 1
(y == -1) ? .yellow : .gray,
// Front face (+Z): green if z = 1, gray for z = 0 or -1
(z == 1) ? .green : .gray,
// Back face (-Z): blue if z = -1, gray for z = 0 or 1
(z == -1) ? .blue : .gray
]
//        print("Position (\(x), \(y), \(z)): Colors = \(colors)")  // Debugging
return colors.map { createMaterial(color: $0) }
}

private func createMaterial(color: UIColor) ->  SCNMaterial {
let material = SCNMaterial()
print("Applying material with color: \(color)")
material.diffuse.contents = color.withAlphaComponent(1.0)
material.specular.contents = UIColor.white
material.shininess = 100
material.lightingModel = .phong

return material
}

private func configureLights() {
// Ambient light for base illumination
let ambientLight = SCNLight()
ambientLight.type = .ambient
ambientLight.intensity = 500
let ambientLightNode = SCNNode()
ambientLightNode.light = ambientLight
rootNode.addChildNode(ambientLightNode)

// Array of positions and directions for the 6 lights
let positions: [(SCNVector3, SCNVector3)] = [
(SCNVector3(0, 10, 0), SCNVector3(0, -1, 0)),  // Top
(SCNVector3(0, -10, 0), SCNVector3(0, 1, 0)),   // Bottom
(SCNVector3(10, 0, 0), SCNVector3(-1, 0, 0)),   // Right
(SCNVector3(-10, 0, 0), SCNVector3(1, 0, 0)),   // Left
(SCNVector3(0, 0, 10), SCNVector3(0, 0, -1)),   // Front
(SCNVector3(0, 0, -10), SCNVector3(0, 0, 1))    // Back
]

for (position, direction) in positions {
let light = SCNLight()
light.type = .directional
light.intensity = 1000
light.color = UIColor.white
let lightNode = SCNNode()
lightNode.light = light
lightNode.position = position
lightNode.eulerAngles = SCNVector3(
atan2(direction.y, direction.z),
atan2(direction.x, direction.z),
0
) // Orient toward the center
rootNode.addChildNode(lightNode)
}
}

required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
< /code>
changekitview: < /p>
import SwiftUI
import SceneKit

struct SceneKitView: UIViewRepresentable {
func makeUIView(context: Context) -> SCNView {
let view = SCNView()
view.scene = CuboScene()  // Use the created scene
view.allowsCameraControl = true  // Allow camera movement with touch
view.autoenablesDefaultLighting = false  // Disable default lighting
view.backgroundColor = .clear

// Configure an initial camera
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
cameraNode.position = SCNVector3(x: 5, y: 5, z: 5)  // Diagonal position to see all faces
cameraNode.look(at: SCNVector3(0, 0, 0))  // Point to the cubes center
view.pointOfView = cameraNode

return view
}

func updateUIView(_ uiView: SCNView, context: Context) {}
}

#Preview {
SceneKitView()
}
Вот как генерируются цвета куба Rubik:

Я пробовал много разных вещей, но я не могу сделать это правильно.

Подробнее здесь: https://stackoverflow.com/questions/794 ... -cube-test
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «IOS»