Amit Kalra
Amit Kalra

Reputation: 4113

How to make SCNNode rotate/spin horizontally

I'm trying to make my SCNNode automatically rotate horizontally by itself. This is the code I have so far:

box.scale = SCNVector3(x: 0.26, y: 0.26, z: 0.26)
box.position = SCNVector3(0.15, 3.85, -3)

How do I make this box spin horizontally automatically? And for a plus, is there a way to make it happen with user interaction enabled too? Thanks!

Update: If I didn't sound as clear, this is what I mean: You know when you spin a basketball on your finger and how it's spinning horizontally? That's the effect I'm trying to achieve! Thanks!

Upvotes: 2

Views: 4025

Answers (2)

user3069232
user3069232

Reputation: 8995

SwiftUI using SceneView updated the accepted answer with some slightly newer syntax.

Works well on iOS14/iOS15

    let oldTransform = cubeNode.transform
    let rotation = SCNMatrix4MakeRotation(GLKMathDegreesToRadians(90), 0, 1, 0)
    SCNTransaction.begin()
    SCNTransaction.animationDuration = 0.5
    cubeNode.transform = SCNMatrix4Mult(rotation, oldTransform)
    SCNTransaction.commit()

Upvotes: 0

jlsiewert
jlsiewert

Reputation: 3574

You can either

Edit:

let action = SCNAction.repeatForever(SCNAction.rotate(by: .pi, around: SCNVector3(0, 1, 0), duration: 5))
box.runAction(action)

You can change the transform like this

let oldTransform = box.transform
let rotation = SCNMatrix4MakeRotation(axis.x, axis.y, axis.z angle)
SCNTransaction.begin()
SCNTransaction.animationDuration = 0.5
box.transform = SCNMatrix4Mult(rotation, oldTransform)
SCNTransaction.commit()

To use user input you can for example change the angle of the rotation or the duration with a gesture recognizter

Upvotes: 6

Related Questions