Drag Rotate a Node around a fixed point
The following code simulates a prize wheel that spins based on touch. As the user's finger moves, the wheel rotates proportionately to the speed of the finger. When the user swipes on the wheel, the wheel will spin proportionately to the velocity of the swipe. You can change the angularDamping
property of the physics body to slow or increase the rate at which the wheel comes to a stop.
class GameScene: SKScene {
var startingAngle:CGFloat?
var startingTime:TimeInterval?
override func didMove(to view: SKView) {
let wheel = SKSpriteNode(imageNamed: "Spaceship")
wheel.name = "wheel"
wheel.setScale(0.5)
wheel.physicsBody = SKPhysicsBody(circleOfRadius: wheel.size.width/2)
// Change this property as needed (increase it to slow faster)
wheel.physicsBody!.angularDamping = 0.25
wheel.physicsBody?.pinned = true
wheel.physicsBody?.affectedByGravity = false
addChild(wheel)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in:self)
let node = atPoint(location)
if node.name == "wheel" {
let dx = location.x - node.position.x
let dy = location.y - node.position.y
// Store angle and current time
startingAngle = atan2(dy, dx)
startingTime = touch.timestamp
node.physicsBody?.angularVelocity = 0
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches{
let location = touch.location(in:self)
let node = atPoint(location)
if node.name == "wheel" {
let dx = location.x - node.position.x
let dy = location.y - node.position.y
let angle = atan2(dy, dx)
// Calculate angular velocity; handle wrap at pi/-pi
var deltaAngle = angle - startingAngle!
if abs(deltaAngle) > CGFloat.pi {
if (deltaAngle > 0) {
deltaAngle = deltaAngle - CGFloat.pi * 2
}
else {
deltaAngle = deltaAngle + CGFloat.pi * 2
}
}
let dt = CGFloat(touch.timestamp - startingTime!)
let velocity = deltaAngle / dt
node.physicsBody?.angularVelocity = velocity
// Update angle and time
startingAngle = angle
startingTime = touch.timestamp
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
startingAngle = nil
startingTime = nil
}
}
Rotation along fixed point on drag
You can make the object draggable, and set a dragBoundFunc. i.e., http://jsfiddle.net/bighostkim/7Q5Hd/
dragBoundFunc: function (pos) {
var pos = stage.getMousePosition();
var xd = this.getX() - pos.x ;
var yd = this.getY() - pos.y ;
var radian = Math.atan2(yd, xd);
this.setRotation(degree);
return {
x: this.getX(),
y: this.getY()
}
}
Rotation along fixed point on drag
You can make the object draggable, and set a dragBoundFunc. i.e., http://jsfiddle.net/bighostkim/7Q5Hd/
dragBoundFunc: function (pos) {
var pos = stage.getMousePosition();
var xd = this.getX() - pos.x ;
var yd = this.getY() - pos.y ;
var radian = Math.atan2(yd, xd);
this.setRotation(degree);
return {
x: this.getX(),
y: this.getY()
}
}
How do I rotate a SpriteNode with a one finger “touch and drag”
The Math was wrong. Here's what I learned you need:
How this looks in swift:
if point.x.sign == .minus {
angle = atan(point.y/point.x) + CGFloat.pi/2
} else {
angle = atan(point.y/point.x) + CGFloat.pi/2 + CGFloat.pi
}
Also, you have to get the coordinates of another object in the scene because the entire coordinate system rotates with the object:
let body = parent?.childNode(withName: "objectInScene")
let point = touch.location(in: body!)
How to make object rotate with drag, how to get a rotate point around the origin use sin or cos?
There are two problems with your approach:
The origin shouldn't be where the user clicked (that is the handle), but a fixed point in your div:
target_wp=$(e.target).closest('.draggable_wp');
//var o_x = e.pageX, o_y = e.pageY; // origin point
var o_x = target_wp.offset().left,
o_y = target_wp.offset().top; // origin pointYou will use the clicked point also, but for something else (more later):
var h_x = e.pageX, h_y = e.pageY; // clicked point
Finally, the origin should be fixed (i.e. should not change between rotations). One way of doing so is preserving it as a
data
attribute (there are other options though):if ( !target_wp.data("origin") )
target_wp.data("origin", { left:target_wp.offset().left,
top:target_wp.offset().top });
var o_x = target_wp.data("origin").left,
o_y = target_wp.data("origin").top; // origin pointUpdate: One good candidate for the origin is the CSS property
transform-origin
, if present - it should ensure that the mouse follow the handle as closely as possible. This is an experimental feature, however, so the actual resulsts may vary. P.S. I'm not sure setting it to50% 50%
is a good idea, since the transformation itself may vary the element's width and height, top and left.To find the angle, you should not call
atan2
on the mouse point only, since it will only calculate the angle between that point and the top left corner of the page. You want the angle between that point and the origin:var s_rad = Math.atan2(s_y - o_y, s_x - o_x); // current to origin
That'll lead you halfway, but it will still behave oddly (it will rotate around the element origin, but not following the handle as you expect). To make it follow the handle, you should adjust the angle in relation to the clicked point - which will serve as a base for the amount to rotate:
s_rad -= Math.atan2(h_y - o_y, h_x - o_x); // handle to origin
After that you get the rotation working (for one user iteration at least).
You'll notice the handle does not follow the mouse precisely, and the reason is the choice of the origin point - defaulting to the element's top/left corner. Adjust it to somewhere inside the element (maybe using a data-
attribute) and it should work as expected.
However, if the user interacts with the handle multiple times, it's not enough to just set the rotation angle, you must update whatever it was during the last iteration. So I'm adding a last_angle
var that will be set on the first click and then added to the final angle during drag:
// on mousedown
last_angle = target_wp.data("last_angle") || 0;
// on mousemove
s_rad += last_angle; // relative to the last one
// on mouseup
target_wp.data("last_angle", s_rad);
Here's the final working example. (Note: I fixed the nesting of your mouse handlers, so they don't get added again after each click)
$(function () { var dragging = false, target_wp, o_x, o_y, h_x, h_y, last_angle; $('.handle').mousedown(function (e) { h_x = e.pageX; h_y = e.pageY; // clicked point e.preventDefault(); e.stopPropagation(); dragging = true; target_wp = $(e.target).closest('.draggable_wp'); if (!target_wp.data("origin")) target_wp.data("origin", { left: target_wp.offset().left, top: target_wp.offset().top }); o_x = target_wp.data("origin").left; o_y = target_wp.data("origin").top; // origin point last_angle = target_wp.data("last_angle") || 0; })
$(document).mousemove(function (e) { if (dragging) { var s_x = e.pageX, s_y = e.pageY; // start rotate point if (s_x !== o_x && s_y !== o_y) { //start rotate var s_rad = Math.atan2(s_y - o_y, s_x - o_x); // current to origin s_rad -= Math.atan2(h_y - o_y, h_x - o_x); // handle to origin s_rad += last_angle; // relative to the last one var degree = (s_rad * (360 / (2 * Math.PI))); target_wp.css('-moz-transform', 'rotate(' + degree + 'deg)'); target_wp.css('-moz-transform-origin', '50% 50%'); target_wp.css('-webkit-transform', 'rotate(' + degree + 'deg)'); target_wp.css('-webkit-transform-origin', '50% 50%'); target_wp.css('-o-transform', 'rotate(' + degree + 'deg)'); target_wp.css('-o-transform-origin', '50% 50%'); target_wp.css('-ms-transform', 'rotate(' + degree + 'deg)'); target_wp.css('-ms-transform-origin', '50% 50%'); } } }) // end mousemove $(document).mouseup(function (e) { dragging = false var s_x = e.pageX, s_y = e.pageY; // Saves the last angle for future iterations var s_rad = Math.atan2(s_y - o_y, s_x - o_x); // current to origin s_rad -= Math.atan2(h_y - o_y, h_x - o_x); // handle to origin s_rad += last_angle; target_wp.data("last_angle", s_rad); })})
.draggable_wp { position: absolute; left: 150px; top: 150px;}.el { width: 25px; height: 50px; background-color: yellow;}.handle { position: absolute; left:0; top:-75; width: 25px; height: 25px; background-color: blue;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><div class="draggable_wp"> <div class="el"></div> <div class="handle"></div></div>
Rotating around anchor point in SceneKit
The pivot
property is what you're looking for. Or, since modern SceneKit often works better / makes nicer Swift / interoperates easier with ARKit when you use SIMD types, the simdPivot
property.
Note this bit in the docs:
Changing the pivot transform alters these behaviors in many useful ways. You can:
- Offset the node’s contents relative to its position. For example, by setting the pivot to a translation transform you can position a node containing a sphere geometry relative to where the sphere would rest on a floor instead of relative to its center.
- Move the node’s axis of rotation. For example, with a translation transform you can cause a node to revolve around a faraway point instead of rotating around its center, and with a rotation transform you can tilt the axis of rotation.
Similarly, for a cylinder, you can make its pivot a transform matrix that translates the origin by half its height, giving it an "anchor point" (for position and rotation changes) at one end instead of in the center. Something like this (untested):
let cylinder = SCNCylinder(radius: /*...*/, height: /*...*/)
let cylinderNode = SCNNode(geometry: cylinder)
cylinderNode.simdPivot = float4x4(translation: cylinder.height / 2)
extension float4x4 {
init(translation vector: float3) {
self.init(float4(1, 0, 0, 0),
float4(0, 1, 0, 0),
float4(0, 0, 1, 0),
float4(vector.x, vector.y, vector.z, 1))
}
}
More generally, whenever you're using a scene-graph / transform-hierarchy based graphics framework, any time you find yourself doing math depending on one transform (rotation, translation, etc) to affect another, it's always good to check for API that can do that math for you — because doing that kind of math is what transform hierarchy is all about.
And if there's not an API fairly specific to what you need, remember that the hierarchy itself is good for making dependent transforms. For example, if you want one node to follow a circular orbit around another, you don't need to set its position using sines and cosines... just make it the child of another node, and rotate that other node.
In this case, pivot is a convenience equivalent to using the node hierarchy. You could just as well create an intermediate node and move the cylinder within it (something like this):
let cylinder = SCNCylinder(radius: /*...*/, height: /*...*/)
let cylinderNode = SCNNode(geometry: cylinder)
let offsetNode = SCNNode()
offsetNode.addChildNode(cylinderNode)
cylinderNode.simdPosition.y = cylinder.height / 2
offsetNode.position = /*...*/ // set world-space position of end of cylinder
offsetNode.eulerAngles.x = /*...*/ // rotate cylinder around its end
Related Topics
Swift Update Label (With HTML Content) Takes 1Min
Only First Track Playing of Avmutablecomposition()
Constant Speed Orbit Around Point with Sknode
Non-Strong References Not Working in Playground
How to Create an Array of Functions
Convert Generic Free Function into Array Extension
Swift, How to Play Sound When Press a Button
Iso8601 Date JSON Decoding Using Swift4
How to Hide Labels in iOS-Charts
Swiftui: Prevent Image() from Expanding View Rect Outside of Screen Bounds
Back Button Image - What Is It Called in Swift
Cannot Invoke 'Join' with an Argument List of Type (String, [String]) in Swift 2.0
How to Bind Different Associated Values in a Swift Enum to the Same Var
Know When an Iteration Over Array with Async Method Is Finished
How to Create Several Cached Uicolor