如何在swift中使用SKConstraint

时间:2023-01-23 07:44:42

I have a moving camera in my scene, which always follows my player. But I also have some other content(On screen controls) which I want to stay in a single place on the screen, but when the camera moves, The controls are moving away to. How would I go about doing this. I have searched a lot, and found the SKConstraint, but I couldn't find any tutorials to use it in swift 3.

我的场景中有一个移动的摄像头,它始终跟随我的播放器。但我还有一些其他的内容(屏幕控制),我想留在屏幕上的一个地方,但当相机移动时,控件正在移动到。我该怎么做呢?我搜索了很多,并找到了SKConstraint,但我找不到任何教程在swift 3中使用它。

Should I be using the SKConstraint? If yes, how can I use it, if no, how do I keep the controls at a certain position on the screen at all times.

我应该使用SKConstraint吗?如果是,我该如何使用它,如果不是,我如何将控件始终保持在屏幕上的某个位置。

I also know that I could change the position of the controls in the update method, but I do not want to do that as there are many on screen controls, and I try to refrain from writing code in the update method as much as possible.

我也知道我可以在更新方法中更改控件的位置,但我不想这样做,因为屏幕控件有很多,我尽量避免在更新方法中编写代码。

Any help would be appreciated, thanks!

任何帮助将不胜感激,谢谢!

1 个解决方案

#1


1  

You can use an SKConstraint to cause a camera to follow a character.

您可以使用SKConstraint使摄像机跟随角色。

First, create a camera node and a hero and add them to the scene

首先,创建一个摄像机节点和一个英雄,并将它们添加到场景中

let cameraNode = SKCameraNode()
let hero = SKSpriteNode(imageNamed: "Spaceship")

addChild(hero)
camera = cameraNode
addChild(cameraNode)

Next, create a constraint and assign it to the camera node's constraints property

接下来,创建一个约束并将其分配给摄像机节点的constraints属性

let range = SKRange(constantValue:0)
let constraint = SKConstraint.distance(range, to: hero)
cameraNode.constraints = [constraint]

Lastly, if you have controls or labels that need to be at fixed locations relative to the camera, you can add them to the camera node

最后,如果您的控件或标签需要位于相对于相机的固定位置,则可以将它们添加到相机节点

let label = SKLabelNode(text: "Score: 123")

// Position the label relative to the camera node
label.position = CGPoint(x: 100, y: 100)
cameraNode.addChild(label)

#1


1  

You can use an SKConstraint to cause a camera to follow a character.

您可以使用SKConstraint使摄像机跟随角色。

First, create a camera node and a hero and add them to the scene

首先,创建一个摄像机节点和一个英雄,并将它们添加到场景中

let cameraNode = SKCameraNode()
let hero = SKSpriteNode(imageNamed: "Spaceship")

addChild(hero)
camera = cameraNode
addChild(cameraNode)

Next, create a constraint and assign it to the camera node's constraints property

接下来,创建一个约束并将其分配给摄像机节点的constraints属性

let range = SKRange(constantValue:0)
let constraint = SKConstraint.distance(range, to: hero)
cameraNode.constraints = [constraint]

Lastly, if you have controls or labels that need to be at fixed locations relative to the camera, you can add them to the camera node

最后,如果您的控件或标签需要位于相对于相机的固定位置,则可以将它们添加到相机节点

let label = SKLabelNode(text: "Score: 123")

// Position the label relative to the camera node
label.position = CGPoint(x: 100, y: 100)
cameraNode.addChild(label)