jjzjj

ios - 将相机移动到点击的 SCNNode

coder 2024-01-28 原文

我正在使用 SceneKitSwift 尝试移动相机,使其“聚焦”在所选节点上。我知道我启用了 defaultCameraController,但我试图通过 dollyrotatetranslateInCameraSpaceBy 调整相机的位置,但没有动画过渡 -它刚刚跳到新位置。

相机是否可以像 Google map 滑动/然后缩放到搜索到的位置那样滑动到位?

任何帮助将不胜感激:)

这是我的代码:

import UIKit
import SceneKit

class ViewController: UIViewController {

var gameView: SCNView!
var scene: SCNScene!
var cameraNode: SCNNode!

override func viewDidLoad() {
    super.viewDidLoad()

    // Scene
    scene = SCNScene()

    // Camera
    cameraNode = SCNNode()
    cameraNode.camera = SCNCamera()
    cameraNode.position = SCNVector3(0, 0, 10)
    scene.rootNode.addChildNode(cameraNode)

    // Light


    /*
    let lightNode = SCNNode()
    lightNode.light = SCNLight()
    lightNode.light?.type = .omni
    lightNode.position = SCNVector3(0, 10, 2)
    scene.rootNode.addChildNode(lightNode)
    */
    // Stars
    //let stars = SCNParticleSystem(named: "starsParticles.scnp", inDirectory: nil)!
    //scene.rootNode.addParticleSystem(stars)

    // Earth
    let earthNode = itemPlate()
    earthNode.position = SCNVector3(0, 0, 0)
    scene.rootNode.addChildNode(earthNode)

    // Create orbiting moonOne
    let moonNodeOne = itemPlate()
    moonNodeOne.position = SCNVector3(3, 0, 0)
    earthNode.addChildNode(moonNodeOne)

    // Create orbiting moonOne
    let moonNodeTwo = itemPlate()
    moonNodeTwo.position = SCNVector3(5, 3, 2)
    earthNode.addChildNode(moonNodeTwo)

    // Create orbiting moonOne
    let moonNodeThree = itemPlate()
    moonNodeThree.position = SCNVector3(-4, -3, 5)
    earthNode.addChildNode(moonNodeThree)

    // Scene formation
    gameView = self.view as! SCNView
    gameView.scene = scene
    gameView.showsStatistics = true
    gameView.allowsCameraControl = true
    gameView.autoenablesDefaultLighting = true
    gameView.defaultCameraController.interactionMode = .fly
    gameView.defaultCameraController.inertiaEnabled = true
    gameView.defaultCameraController.maximumVerticalAngle = 89
    gameView.defaultCameraController.minimumVerticalAngle = -89
    scene.background.contents = UIImage(named: "orangeBg.jpg")

}

override var prefersStatusBarHidden: Bool {
    return true
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first!
    let location = touch.location(in: gameView)
    let hitList = gameView.hitTest(location, options: nil)

    if let hitObject = hitList.first {
        let node = hitObject.node

        // Update camera position
        //gameView.defaultCameraController.translateInCameraSpaceBy(x: node.position.x, y: node.position.y, z: node.position.z + 5)
        let onScreenPoint:CGPoint = CGPoint(x: 1.0, y: 1.0)
        let viewport:CGSize = CGSize(width: 50, height: 50)

        gameView.defaultCameraController.dolly(by: 1.0, onScreenPoint: onScreenPoint, viewport: viewport)


        //let newCameraPosition = SCNVector3Make(node.position.x, node.position.y, node.position.z + 10)
        print("NODE_HIT_OBJECT_COORDS: \(node.position.x), \(node.position.y) \(node.position.y)")

        //let moveToAction = SCNAction.move(by: newCameraPosition, duration: 1.0)


    }
}

最佳答案

你可以在你的代码中实现这样的方法(抱歉,我使用的是 macOS 项目而不是 iOS,但它几乎是一样的):

func handleClick(_ gestureRecognizer: NSGestureRecognizer) {

    let scnView = self.view as! SCNView       
    let p = gestureRecognizer.location(in: scnView)
    let hitResults = scnView.hitTest(p, options: [:])

    if hitResults.count > 0 {

        let result = hitResults[0]
        let nodePosition = result.node.position.z
        var matrix = matrix_identity_float4x4

        SCNTransaction.begin()
        SCNTransaction.animationDuration = 1.5       // duration in seconds
        matrix.columns.3.z = Float(nodePosition + 5.0)
        scnView.pointOfView?.position.z = CGFloat(matrix.columns.3.z)
        SCNTransaction.commit()
    }
} 

或者,作为第二个逻辑选项,您可以使用 SceneKit 的 constraints :

func handleClick(_ gestureRecognizer: NSGestureRecognizer) {

    let scnView = self.view as! SCNView
    let p = gestureRecognizer.location(in: scnView)
    let hitResults = scnView.hitTest(p, options: [:])

    if hitResults.count > 0 {

        let result = hitResults[0]
        let nodePosition = result.node
        let constraint1 = SCNLookAtConstraint(target: nodePosition)
        let constraint2 = SCNDistanceConstraint(target: nodePosition)
        constraint2.minimumDistance = 5
        constraint2.maximumDistance = 9

        SCNTransaction.begin()
        SCNTransaction.animationDuration = 1.5
        scnView.pointOfView?.constraints = [constraint2, constraint1]
        SCNTransaction.commit()
    }
}

附言这两种方法不是开箱即用的解决方案,而是提示如何实现您想要的。

关于ios - 将相机移动到点击的 SCNNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56736387/

有关ios - 将相机移动到点击的 SCNNode的更多相关文章

  1. ruby - 多次弹出/移动 ruby​​ 数组 - 2

    我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby​​数组,我们在StackOverflow上找到一

  2. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  3. ruby-on-rails - 如何重命名或移动 Rails 的 README_FOR_APP - 2

    当我在我的Rails应用程序根目录中运行rakedoc:app时,API文档是使用/doc/README_FOR_APP作为主页生成的。我想向该文件添加.rdoc扩展名,以便它在GitHub上正确呈现。更好的是,我想将它移动到应用程序根目录(/README.rdoc)。有没有办法通过修改包含的rake/rdoctask任务在我的Rakefile中执行此操作?是否有某个地方可以查找可以修改的主页文件的名称?还是我必须编写一个新的Rake任务?额外的问题:Rails应用程序的两个单独文件/README和/doc/README_FOR_APP背后的逻辑是什么?为什么不只有一个?

  4. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  5. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  6. ruby-on-rails - rbenv:从 RVM 移动到 rbenv 后,在 Jenkins 执行 shell 中找不到命令 - 2

    我从Ubuntu服务器上的RVM转移到rbenv。当我使用RVM时,使用bundle没有问题。转移到rbenv后,我在Jenkins的执行shell中收到“找不到命令”错误。我内爆并删除了RVM,并从~/.bashrc'中删除了所有与RVM相关的行。使用后我仍然收到此错误:rvmimploderm~/.rvm-rfrm~/.rvmrcgeminstallbundlerecho'exportPATH="$HOME/.rbenv/bin:$PATH"'>>~/.bashrcecho'eval"$(rbenvinit-)"'>>~/.bashrc.~/.bashrcrbenvversions

  7. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

  8. ruby - 如何将相同的相邻数字分组 - 2

    如果至少有两个相邻的数字相同,格式为,我需要打包.这是我的输入:[2,2,2,3,4,3,3,2,4,4,5]以及预期的输出:"2:3,3,4,3:2,2,4:2,5"到目前为止我试过:a=[1,1,1,2,2,3,2,3,4,4,5]a.each_cons(2).any?do|s,t|ifs==t如果相等,也许可以尝试计数器,但那是行不通的。 最佳答案 您可以使用Enumerable#chunk_while(如果你使用的是Ruby>=2.3):a.chunk_while{|a,b|a==b}.flat_map{|chunk|chu

  9. ruby - 为 IO::popen 拯救 "command not found" - 2

    当我将IO::popen与不存在的命令一起使用时,我在屏幕上打印了一条错误消息:irb>IO.popen"fakefake"#=>#irb>(irb):1:commandnotfound:fakefake有什么方法可以捕获此错误,以便我可以在脚本中进行检查? 最佳答案 是:升级到ruby​​1.9。如果您在1.9中运行它,则会引发Errno::ENOENT,您将能够拯救它。(编辑)这是在1.8中的一种hackish方式:error=IO.pipe$stderr.reopenerror[1]pipe=IO.popen'qwe'#

  10. ruby - IO::EAGAINWaitReadable:资源暂时不可用 - 读取会阻塞 - 2

    当我尝试使用“套接字”库中的方法“read_nonblock”时出现以下错误IO::EAGAINWaitReadable:Resourcetemporarilyunavailable-readwouldblock但是当我通过终端上的IRB尝试时它工作正常如何让它读取缓冲区? 最佳答案 IgetthefollowingerrorwhenItrytousethemethod"read_nonblock"fromthe"socket"library当缓冲区中的数据未准备好时,这是预期的行为。由于异常IO::EAGAINWaitReadab

随机推荐