I wish to access a variable outside of it's scope. (A snippet of the relevant code is posted). Within the #IBAction ,the sphereNode.runAction(moveUp) is not recognised.
I cannot simply declare sphereNode global as it is dependant upon the sphereGeometry declaration.
override func viewDidLoad() {
super.viewDidLoad()
//Added our first shape = sphere
let sphereGeometry = SCNSphere(radius: 1.0)
let sphereNode = SCNNode(geometry: sphereGeometry)
sphereNode.position = SCNVector3Make(0, 0, 0)
sphereGeometry.firstMaterial!.diffuse.contents = UIColor.redColor()
sphereGeometry.firstMaterial!.specular.contents = UIColor.whiteColor()
scene.rootNode.addChildNode(sphereNode)
}
#IBAction func animateButton(sender: AnyObject) {
let moveUp = SCNAction.moveByX(0.0, y: 1.0, z: 0.0, duration: 1.0)
sphereNode.runAction(moveUp)
}
}`
Beginner programmer so please simple explanations are appreciated - thanks in advance.
What you need here is an instance variable.
Variables cannot be used outside their scope (and eventually you'll learn this is a really great thing). But we can expand our variable's scope:
class YourViewController: UIViewController {
var sphereNode: SNNode?
override func viewDidLoad() {
super.viewDidLoad()
//Added our first shape = sphere
let sphereGeometry = SCNSphere(radius: 1.0)
self.sphereNode = SCNNode(geometry: sphereGeometry)
self.sphereNode?.position = SCNVector3Make(0, 0, 0)
sphereGeometry.firstMaterial!.diffuse.contents = UIColor.redColor()
sphereGeometry.firstMaterial!.specular.contents = UIColor.whiteColor()
scene.rootNode.addChildNode(sphereNode)
}
#IBAction func animateButton(sender: AnyObject) {
let moveUp = SCNAction.moveByX(0.0, y: 1.0, z: 0.0, duration: 1.0)
self.sphereNode?.runAction(moveUp)
}
}
Related
I've encountered an issue using a UIProgressView where low values (1% - about 10%) look off. You can see with the example above that 97% looks accurate while 2% does not.
Here's the code for setting colors:
self.progressView.trackTintColor = UIColor.green.withAlphaComponent(0.3)
self.progressView.tintColor = UIColor.green.withAlphaComponent(1.0)
But, if I comment out the trackTintColor or the tintColor, then the 2% looks correct. Why when using these together does it cause this issue? Just an Xcode bug? Has anyone resolved this before?
I've experienced the same issue in my project. For me it's fixed by using progressTintColor instead of tintColor.
progressView.progressTintColor = UIColor.green.withAlphaComponent(1.0)
progressView.trackTintColor = UIColor.green.withAlphaComponent(0.3)
you need to create color image
SWIFT 3 Example:
class ViewController: UIViewController {
#IBOutlet weak var progressView: UIProgressView!
#IBAction func lessButton(_ sender: UIButton) {
let percentage = 20
let invertedValue = Float(100 - percentage) / 100
progressView.setProgress(invertedValue, animated: true)
}
#IBAction func moreButton(_ sender: UIButton) {
let percentage = 80
let invertedValue = Float(100 - percentage) / 100
progressView.setProgress(invertedValue, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
//create gradient view the size of the progress view
let gradientView = GradientView(frame: progressView.bounds)
//convert gradient view to image , flip horizontally and assign as the track image
progressView.trackImage = UIImage(view: gradientView).withHorizontallyFlippedOrientation()
//invert the progress view
progressView.transform = CGAffineTransform(scaleX: -1.0, y: -1.0)
progressView.progressTintColor = UIColor.black
progressView.progress = 1
}
}
extension UIImage{
convenience init(view: UIView) {
UIGraphicsBeginImageContext(view.frame.size)
view.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.init(cgImage: (image?.cgImage)!)
}
}
#IBDesignable
class GradientView: UIView {
private var gradientLayer = CAGradientLayer()
private var vertical: Bool = false
override func draw(_ rect: CGRect) {
super.draw(rect)
// Drawing code
//fill view with gradient layer
gradientLayer.frame = self.bounds
//style and insert layer if not already inserted
if gradientLayer.superlayer == nil {
gradientLayer.startPoint = CGPoint(x: 0, y: 0)
gradientLayer.endPoint = vertical ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0)
gradientLayer.colors = [UIColor.green.cgColor, UIColor.red.cgColor]
gradientLayer.locations = [0.0, 1.0]
self.layer.insertSublayer(gradientLayer, at: 0)
}
}
}
Below is the function that loads my object. Whenever I run the app, the object loads perfectly but when I try getting close or moving around, it moves along with the camera. I tried loading using hit test, it works but then collisions do not work when I use hit results and world positioning.
func addBackboard() {
guard let bucketScene = SCNScene(named:"art.scnassets/BucketBlue.scn") else {
return
}
guard let bucketNode = bucketScene.rootNode.childNode(withName: "tube", recursively: false) else {
return
}
bucketNode.scale = SCNVector3Make(0.5, 0.5, 0.5);
bucketNode.position = SCNVector3(x: 0, y: -3.5, z: -5)
let physicsShape = SCNPhysicsShape(node: bucketNode, options: [SCNPhysicsShape.Option.type: SCNPhysicsShape.ShapeType.concavePolyhedron])
let physicsBody = SCNPhysicsBody(type: .static, shape: physicsShape)
bucketNode.physicsBody = physicsBody
sceneView.scene.rootNode.addChildNode(bucketNode)
}
I found some Apple documentation that might help. Summary: "To track the static positions and orientations of real or virtual objects relative to the camera, create anchor objects and use the add(anchor:) method to add them to your AR session."
And then, did you implement the ARSCNViewDelegate methods?
I suppose your code should look like the following one:
class ViewController: UIViewController, ARSCNViewDelegate {
#IBOutlet var sceneView: ARSCNView!
//.................................
func addBackboard() {
sceneView.delegate = self
guard let scene = SCNScene(named:"art.scnassets/BucketBlue.scn") else {
return
}
sceneView.scene = scene
let bucketNode = SCNNode()
bucketNode.geometry = SCNTube()
bucketNode.scale = SCNVector3(0.5, 0.5, 0.5)
bucketNode.position = SCNVector3(x: 0, y: -3.5, z: -5)
let physicsShape = SCNPhysicsShape(
node: bucketNode,
options: [SCNPhysicsShape.Option.type: SCNPhysicsShape.ShapeType.concavePolyhedron])
let physicsBody = SCNPhysicsBody(type: .static, shape: physicsShape)
bucketNode.physicsBody = physicsBody
scene.rootNode.addChildNode(bucketNode)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let configuration = ARWorldTrackingConfiguration()
sceneView.session.run(configuration)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
sceneView.session.pause()
}
}
I am trying to access the childnode: boxNode, and then rotate the node using the input from a pan gesture recognizer. How should I access this node so I can manipulate it? Should I declare the cube node in a global scope and modify that way? I am new to Swift so I apologize if this code looks sloppy. I would like to add rotation actions inside of my panGesture() function. Thanks!
import UIKit
import SceneKit
class GameViewController: UIViewController {
var scnView: SCNView!
var scnScene: SCNScene!
override func viewDidLoad() {
super.viewDidLoad()
setupView()
setupScene()
}
// override var shouldAutorotate: Bool {
// return true
// }
//
// override var prefersStatusBarHidden: Bool {
// return true
// }
func setupView() {
scnView = self.view as! SCNView
}
func setupScene() {
scnScene = SCNScene()
scnView.scene = scnScene
scnView.backgroundColor = UIColor.blueColor()
initCube()
initLight()
initCamera()
}
func initCube () {
var cubeGeometry:SCNGeometry
cubeGeometry = SCNBox(width: 1.0, height: 1.0, length: 1.0, chamferRadius: 0.0)
let boxNode = SCNNode(geometry: cubeGeometry)
scnScene.rootNode.addChildNode(boxNode)
}
func initLight () {
let light = SCNLight()
light.type = SCNLightTypeAmbient
let lightNode = SCNNode()
lightNode.light = light
light.castsShadow = false
lightNode.position = SCNVector3(x: 1.5, y: 1.5, z: 1.5)
scnScene.rootNode.addChildNode(lightNode)
}
func initCamera () {
let camera = SCNCamera()
let cameraNode = SCNNode()
cameraNode.camera = camera
cameraNode.position = SCNVector3(x: 0.0, y: 0.0, z: 5.0)
scnScene.rootNode.addChildNode(cameraNode)
}
func initRecognizer () {
let panTestRecognizer = UIPanGestureRecognizer(target: self, action: #selector(GameViewController.panGesture(_:)))
scnView.addGestureRecognizer(panTestRecognizer)
}
//TAKE GESTURE INPUT AND ROTATE CUBE ACCORDINGLY
func panGesture(sender: UIPanGestureRecognizer) {
//let translation = sender.translationInView(sender.view!)
}
}
First of all you should update your Xcode. It looks like this is an older Swift version you are using. SCNLightTypeAmbient is .ambient in Swift 3.
So the way you should go is by giving your nodes names to identify them:
myChildNode.name = "FooChildBar"
and then you can call on your parent node
let theNodeYouAreLookingFor = parentNode.childNode(withName: "FooChildBar", recursively: true)
You can also use this on your scene's root node
let theNodeYouAreLookingFor = scene.rootNode.childNode(withName: "FooChildBar", recursively: true)
which will look at all nodes in your scene and return the one that you gave the name.
I'm working to implement a Zig Zag game and following a set of instructions from an on-line course. I have a swift UIViewController, and I am trying now to use also SCNSceneRenderer (to do the game logic of keeping the game character on the zig-zag path). The code looks like this:
import UIKit
import QuartzCore
import SceneKit
class GameViewController: UIViewController, SCNSceneRenderer{
let scene = SCNScene()
let cameraNode = SCNNode()
var person = SCNNode()
let firstBox = SCNNode()
var goingLeft = Bool()
var tempBox = SCNNode()
var boxNumber = Int()
var prevBoxNumber = Int()
override func viewDidLoad() {
print("Yes -- view did load")
self.createScene()
}
func renderer(render: SCNSceneRenderer, updateAtTime time: TimeInterval){
let deleteBox = self.scene.rootNode.childNode(withName: "\(prevBoxNumber)", recursively: true )
if (deleteBox?.position.x)! > (person.position.x + 1) || (deleteBox?.position.z)! > (person.position.z + 1) {
prevBoxNumber += 1
deleteBox?.removeFromParentNode()
createBox()
}
}
func createBox(){
tempBox = SCNNode(geometry: firstBox.geometry)
let prevBox = scene.rootNode.childNode(withName: "\(boxNumber)", recursively: true )
boxNumber += 1
tempBox.name = "\(boxNumber)"
let randomNumber = arc4random() % 2
switch randomNumber {
case 0:
tempBox.position = SCNVector3Make((prevBox?.position.x)! - firstBox.scale.x, (prevBox?.position.y)!, (prevBox?.position.z)!)
break
case 1:
tempBox.position = SCNVector3Make((prevBox?.position.x)! , (prevBox?.position.y)!, (prevBox?.position.z)! - firstBox.scale.z)
break
default:
break
}
self.scene.rootNode.addChildNode(tempBox)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if goingLeft == false {
person.removeAllActions()
person.runAction(SCNAction.repeatForever(SCNAction.move(by: SCNVector3Make(-100, 0, 0), duration: 20)))
goingLeft = true
} else {
person.removeAllActions()
person.runAction(SCNAction.repeatForever(SCNAction.move(by: SCNVector3Make(0, 0, -100), duration: 20)))
goingLeft = false
}
print("boxNumber is \(boxNumber)")
}
func createScene(){
boxNumber = 0
prevBoxNumber = 0
self.view.backgroundColor = UIColor.orange
let sceneView = self.view as! SCNView
sceneView.delegate = self
sceneView.scene = scene
//Create Person
let personGeo = SCNSphere(radius: 0.2)
person = SCNNode (geometry : personGeo)
let personMat = SCNMaterial()
personMat.diffuse.contents = UIColor.red
personGeo.materials = [personMat]
person.position = SCNVector3Make(0, 1.1, 0)
scene.rootNode.addChildNode(person)
//Create Camera
cameraNode.camera = SCNCamera()
cameraNode.camera?.usesOrthographicProjection = true
cameraNode.camera?.orthographicScale = 3
cameraNode.position = SCNVector3Make(20,20,20)
cameraNode.eulerAngles = SCNVector3Make(-45,45,0)
//let constraint = SCNLookAtConstraint(target: firstBox)
let constraint = SCNLookAtConstraint(target: person)
constraint.isGimbalLockEnabled = true
self.cameraNode.constraints = [constraint]
scene.rootNode.addChildNode(cameraNode)
person.addChildNode(cameraNode)
//Create Box
let firstBoxGeo = SCNBox(width: 1.0, height: 1.5, length: 1.0, chamferRadius: 0)
firstBox.geometry = firstBoxGeo
let boxMaterial = SCNMaterial()
boxMaterial.diffuse.contents = UIColor(red: 0.2, green: 0.8, blue: 0.9, alpha: 1.0)
firstBoxGeo.materials = [boxMaterial]
firstBox.position = SCNVector3Make(0,0,0)
scene.rootNode.addChildNode(firstBox)
firstBox.name = "\(boxNumber)"
for _ in 0...6{
createBox()
}
//Create light
let light = SCNNode()
light.light = SCNLight()
light.light?.type = SCNLight.LightType.directional
light.eulerAngles = SCNVector3Make(-45, 45, 0)
scene.rootNode.addChildNode(light)
//Create light2
let light2 = SCNNode()
light2.light = SCNLight()
light2.light?.type = SCNLight.LightType.directional
light2.eulerAngles = SCNVector3Make(45, 45, 0)
scene.rootNode.addChildNode(light2)
}
}
When I added SCNSceneRenderer I get the following error:
"Type 'GameViewController' cannot conform to protocol 'SCNSceneRenderer' because it has requirements that cannot be satisfied"
Since my GameViewController isn't recognized as a SCNSceneRenderer, I also get an error at this line:
sceneView.delegate = self
the error is "Cannot assign value of type 'GameViewController' to type 'SCNSceneRendererDelegate'
I'm new to swift programming, but this seems like I am trying to implement an interface like in Java, I've been looking at the Swift documentation but don't see what I need to do to make my class be functional as an SCNSceneRenderer. I would appreciate help to solve this problem. Thanks!
When I try to run an action on a sprite I've set a constant for in didMoveToView, I use the same name for it in the touchesBegan function and get a "use of unresolved identifier: "player" error. I have another game where I so the exact same thing and it runs perfectly. Need help! Here is my code:
import SpriteKit
class GameScene: SKScene {
var movingGround : MCTGround!
var fruitGenerator : MCTFruitGen!
var cloudGenerator: MCTCloudGen!
var isStarted = false
override func didMoveToView(view: SKView) {
let player = SKSpriteNode(imageNamed: "koala_idle")
player.position = CGPointMake(95, 150)
addChild(player)
backgroundColor = UIColor(red: 159.0/255.0, green: 201.0/255.0, blue: 244.0/255.0, alpha: 1.0)
movingGround = MCTGround(size: CGSizeMake(view.frame.width, 20))
movingGround.position = CGPointMake(0, view.frame.size.height / 4)
addChild(movingGround)
fruitGenerator = MCTFruitGen(color: UIColor.clearColor(), size: view.frame.size)
fruitGenerator.position = view.center
addChild(fruitGenerator)
let frames = [
SKTexture(imageNamed: "koala_idle"),
SKTexture(imageNamed: "koala_walk01"),
SKTexture(imageNamed: "koala_walk02"),
]
let duration = 1.5 + drand48() * 1.0
let move = SKAction.animateWithTextures(frames, timePerFrame:0.10)
let wait = SKAction.waitForDuration(duration)
let rest = SKAction.setTexture(frames[0])
let sequence = SKAction.sequence([move, rest])
player.runAction(SKAction.repeatActionForever(sequence))
cloudGenerator = MCTCloudGen(color: UIColor.clearColor(), size: view.frame.size)
cloudGenerator.position = view.center
addChild(cloudGenerator)
cloudGenerator.populate(7)
cloudGenerator.startGeneratingWithSpawnTime(1)
}
func start() {
isStarted = true
cloudGenerator.startGeneratingWithSpawnTime(1)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
jumpPlayer()
movingGround.start()
fruitGenerator.startGeneratingFruitEvery(1)
}
override func update(currentTime: CFTimeInterval) {
}
func jumpPlayer() {
let jumpUpAction = SKAction.moveByX(0, y: 40, duration: 0.5)
let jumpDownAction = SKAction.moveByX(0, y: -40, duration: 0.5)
let jumpSequence = SKAction.sequence([jumpUpAction, jumpDownAction])
player.runAction(jumpSequence) // This is where my error is
}
}
Make player a class scope variable (property). Declare it not in a function, but a level above.
var player: SKSpriteNode?
override func didMoveToView(view: SKView) {
player = SKSpriteNode ...
then access it via player?. The safest way.
Your problem is that you are declaring player inside didMoveToView. This makes it private to the didMoveToView method. All you need to do is move let player = SKSpriteNode(imageNamed: "koala_idle") to where you declare movingGround and the other variables with it.
The beginning your code should look like this:
import SpriteKit
class GameScene: SKScene {
var movingGround : MCTGround!
var fruitGenerator : MCTFruitGen!
var cloudGenerator: MCTCloudGen!
let player = SKSpriteNode(imageNamed: "koala_idle")
var isStarted = false
override func didMoveToView(view: SKView) {
player.position = CGPointMake(95, 150)
addChild(player)
Go to File Inspector (right click on the file referenced in the error and select Show File Inspector). In Target Membership make sure your actual app is selected.
In my case only the Test modules were selected.
So as far as I can tell (I'm new to all this), the referenced file was hidden/unregistered with the ViewController.