how to animate points of a UIBezierPath in swift - xcode

I have the following code that draws a custom shape. but i want to animate the points of this shape based on a value in this case the value is called movementX or movementY. So every time i call the function shapeVoid i want the points to move in a spesific direction based on the movement values. how do i do this? see my code below:
class ViewController: UIViewController {
var movementX: CGFloat = 0.0
var movementY: CGFloat = 2.2
override func viewDidLoad() {
super.viewDidLoad()
movementUpdate = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: Selector("ShapeVoid"), userInfo: nil, repeats: true)
}
func ShapeVoid(){
view.layer.addSublayer(shape)
shape.fillColor = UIColor(red: 255/255, green: 120/255, blue: 200/255, alpha: aValue).CGColor
shape.lineWidth = 2
shape.strokeColor = UIColor.blackColor().CGColor
let shapePath = UIBezierPath()
i want to animate the points of my shape path. see below i added a value called movementX/ movmentY to move the points but this didnt do anything. how would i animate points of a path?
shapePath.moveToPoint(CGPointMake(200, 200))
shapePath.addLineToPoint(CGPointMake(230 + movementX, 250 + movementY))
shapePath.addLineToPoint(CGPointMake(150 + movementX, 300 + movementY))
shapePath.addLineToPoint(CGPointMake(100 + movementX, 280 + movementY))
shapePath.closePath()
shape.path = shapePath.CGPath
}
}
thanks in advance let me know if something is unclear :)

Related

SpriteKit animate nodes to specific position

I am building my first game with SpriteKit, written in Swift 3.
I have been trying for hours to accomplish this "winning stars effect", but without any acceptable result yet :/
The effect i am looking for is demonstrated in this video: https://youtu.be/9CeK5_G8T9E
It's not a problem adding one or multiple stars; the problem is to make them move in different directions by different paths to the same location, just like it's done in this video example.
Hope for your help to lead me in the right direction.
Any solution, tutorials, examples etc. is more than welcome.
Thanks for your time.
Took a while but here's something:
import SpriteKit
class GameScene: SKScene {
var sprite = SKSpriteNode()
override func didMove(to view: SKView) {
for _ in 1...15 {
spawnsprite()
}
}
func spawnsprite() {
sprite = SKSpriteNode(color: SKColor.yellow, size: CGSize(width: 50, height: 50))
sprite.position = CGPoint(x: (-size.width/2)+50, y: (-size.height/2)+50)
addChild(sprite)
let destination = CGPoint(x: (size.width/2)-50, y: (size.height/2)-50)
let path = createCurvedPath(from: sprite.position, to: destination, varyingBy: 500)
let squareSpeed = CGFloat(arc4random_uniform(600)) + 200
let moveAction = SKAction.follow(path, asOffset: false, orientToPath: false, speed: squareSpeed)
let rotateAction = SKAction.repeatForever(SKAction.rotate(byAngle: 2 * CGFloat.pi, duration: 2))
sprite.run(SKAction.group([moveAction, rotateAction]))
}
func createCurvedPath(from start: CGPoint, to destination: CGPoint, varyingBy offset: UInt32) -> CGMutablePath {
let pathToMove = CGMutablePath()
pathToMove.move(to: start)
let controlPoint = CGPoint(x: CGFloat(arc4random_uniform(offset)) - CGFloat(offset/2),
y: CGFloat(arc4random_uniform(offset)) - CGFloat(offset/2))
pathToMove.addQuadCurve(to: destination, control: controlPoint)
return pathToMove
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}
There's a lot that can be done to make this nicer (e.g. subclass SKSpriteNode and make the path that the ode follows a property of the sprite itself), but it illustrates the principle.
It could probably also be done with an SKEmitter.

Clock minute-hand disappears when attempting to rotate it

Modus Operandi:
1) Use an UIImageView of a base Clock Image.
2) Add MinuteHand & HourHand sublayers (containing their respective images) to the UIImageView layer.
Problem: both sublayers disappear when attempting to perform a rotation transformation.
Note: 1) I've removed the 'hour' code & ancillary radian calculations to simplify code.
2) The 'center' is the center of the clock. I had adjusted the coordinates to actually pin the hands to the clock's center.
3) The ViewDidLayoutSubviews() appear to be okay. I got the clock + hands.
class ClockViewController:UIViewController {
private let minuteLayer = CALayer()
#IBOutlet weak var clockBaseImageView: UIImageView!
#IBOutlet weak var datePicker: UIDatePicker!
override func viewDidLayoutSubviews() {
guard var minuteSize = UIImage(named: "MinuteHand")?.size,
var hourSize = UIImage(named: "HourHand")?.size
else {
return
}
var contentLayer:CALayer {
return self.view.layer
}
var center = clockBaseImageView.center
// Minute Hand:
minuteLayer.setValue("*** Minute Hand ***", forKey: "id")
minuteSize = CGSize(width: minuteSize.width/3, height: minuteSize.height/3)
minuteLayer.contents = UIImage(named: "MinuteHand")?.cgImage
center = CGPoint(x: 107.0, y: 40.0)
var handFrame = CGRect(origin: center, size: minuteSize)
minuteLayer.frame = handFrame
minuteLayer.contentsScale = clockBaseImageView.layer.contentsScale
minuteLayer.anchorPoint = center
clockBaseImageView.layer.addSublayer(minuteLayer)
}
Here's my problem: Attempting to rotate the minute hand via 0.01 radians:
func set(_ time:Date) {
minuteLayer.setAffineTransform(CGAffineTransform(rotationAngle: .01)) // random value for test.
}
Before rotation attempt:
After attempting to rotate minute hand:
The hand shifted laterally to the right vs rotate.
Why? Perhaps due to the pivot point?
I think this will solve your problem, Take a look and let me know.
import GLKit // Importing GLKit Framework
func set(_ time:Date) {
minuteLayer.transform = CGAffineTransformMakeRotation(CGFloat(GLKMathDegreesToRadians(0.01)))
}
Note: this solution doesn't solve the issue about rotating a CALayer. Instead, it bypasses the issue by replacing the layer with a subview and rotating the subview via:
func set(_ time:Date) {
minuteView.transform = CGAffineTransform(rotationAngle: 45 * CGFloat(M_PI)/180.0)
}
Here's the result:
Still, it would be nice to know how to rotate a CALayer.

How to add more blocks

I tried adding var square, and all the things I did for squareView. But all I am getting is one box falling and the other just standing there. Is there an easier way to add another box which does the same action as squareView?
import UIKit
class interestViewController: UIViewController {
var squareView: UIView!
var square: UIView!
var gravity: UIGravityBehavior!
var animator: UIDynamicAnimator!
var collision: UICollisionBehavior!
override func viewDidLoad() {
super.viewDidLoad()
squareView = UIView(frame: CGRectMake(100, 100, 100, 100))
square = UIView(frame: CGRectMake(200, 100, 100, 100))
squareView.backgroundColor = UIColor.blackColor()
square.backgroundColor = UIColor.blackColor()
view.addSubview(square)
view.addSubview(squareView)
animator = UIDynamicAnimator(referenceView: view)
animator = UIDynamicAnimator(referenceView: view)
gravity = UIGravityBehavior(items: [squareView])
gravity = UIGravityBehavior(items: [square])
animator.addBehavior(gravity)
animator.addBehavior(gravity)
collision = UICollisionBehavior(items: [squareView])
collision = UICollisionBehavior(items: [square])
collision.translatesReferenceBoundsIntoBoundary = true
animator.addBehavior(collision)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This code is sheer nonsense:
gravity = UIGravityBehavior(items: [squareView])
gravity = UIGravityBehavior(items: [square])
animator.addBehavior(gravity)
animator.addBehavior(gravity)
When you set the variable gravity to one behavior and to another behavior right in a row, the first behavior is just thrown out as if it never existed. So naturally when you get around to adding the behaviors, there is only one behavior to add: the one gravity that is left (which you then, even more nonsensically, add twice). So naturally only one block is animated.
Think of it more simply this way:
var x = 0
x = 1
x = 2
Now, what is the value of the variable x? If you think it is 0 and 1 and 2, you have not understood what a variable is.

SKSpriteNode that the correct size

I am trying to draw a SKSpriteNode that is 30 tall and has the width of the viewport. This is the code (inside SKScene):
func floor() -> SKSpriteNode{
let floor = SKSpriteNode(color: SKColor.greenColor(), size: CGSizeMake(self.size.width, 20))
floor.position = CGPointMake(0, 0)
floor.physicsBody = SKPhysicsBody(rectangleOfSize: floor.size)
floor.physicsBody.dynamic = false
return floor
}
The sprite is added to the scene like this:
override func didMoveToView(view: SKView!){
if (!contentCreated){
self.createContents()
contentCreated = true
}
}
func createContents() {
self.backgroundColor = SKColor.blackColor()
self.scaleMode = SKSceneScaleMode.AspectFill
self.addChild(self.floor())
}
The sprite is 30 tall (seemingly), but the length seems to be half of the viewport in width instead of the full width. The code that creates this scene is:
var mainScene = MainScene(size: self.view.frame.size)
spriteView.presentScene(mainScene)
This code is inside a ViewController.
Does anyone know what might be going on?
The default anchorPoint of a sprite node is { 0.5, 0.5 }, which could result in the code above positioning only half of your sprite on the screen. Try setting the anchorPoint to { 0.0, 0.0 } and see if that helps.

Inherited control does not draw

I'm trying to create an own progress bar by subclassing NSProgressIndicator. I wrote the code using a Playground in Xcode 6 and it works fine (the content is being drawn correctly).
As soon as I put the class onto the GUI (either as type for a "Custom View" or for an "Indeterminate Progress Indicator") the control does not draw though the drawRect(dirtyRect: NSRect) method has been overridden and is being called by the framework.
Here's my code:
class AbProgressBar : NSProgressIndicator
{
let drawStep = 10
var rounded: Bool = true
var margin: CGFloat = 4.0
var barColor: NSColor = NSColor.blueColor()
var barBorderColor: NSColor = NSColor.whiteColor()
var borderColor: NSColor = NSColor.grayColor()
var backgroundColor: NSColor = NSColor.blackColor()
init(coder: NSCoder!)
{
println(__FUNCTION__)
super.init(coder: coder)
}
init(frame frameRect: NSRect)
{
println("\(__FUNCTION__) with frame \(frameRect)")
super.init(frame: frameRect)
}
override func drawRect(dirtyRect: NSRect)
{
println(__FUNCTION__)
// Here we calculate the total value area from minValue to maxValue in order to find out the percental width of the inner bar
let area = minValue < 0 && maxValue < 0 ? abs(minValue) + maxValue : abs(maxValue) + abs(minValue)
let currentPercentageFilled: Double = doubleValue >= maxValue ? maxValue : 100 / area * doubleValue
let innerWidth = (frame.width - (margin * 2)) / 100 * currentPercentageFilled
let radOuterX = rounded ? frame.height / 2 : 0
let radOuterY = rounded ? frame.width / 2 : 0
let radInnerX = rounded ? (frame.height - margin) / 2 : 0
let radInnerY = rounded ? innerWidth / 2 : 0
// The inner frame depends on the width filled by the current value
let innerFrame = NSRect(x: frame.origin.x + margin, y: frame.origin.y + margin, width: innerWidth, height: frame.height - (margin * 2))
let pathOuter: NSBezierPath = NSBezierPath(roundedRect: frame, xRadius: radOuterX, yRadius: radOuterY)
let pathInner: NSBezierPath = NSBezierPath(roundedRect: innerFrame, xRadius: radInnerX, yRadius: radInnerY)
let gradientOuter: NSGradient = NSGradient(startingColor: NSColor.whiteColor(), endingColor: backgroundColor)
let gradientInner: NSGradient = NSGradient(startingColor: NSColor.grayColor(), endingColor: barColor)
gradientOuter.drawInBezierPath(pathOuter, angle: 270.0)
if(pathInner.elementCount > 0)
{
gradientInner.drawInBezierPath(pathInner, angle: 270.0)
}
borderColor.set()
pathOuter.stroke()
barBorderColor.set()
pathInner.stroke()
}
}
Using it within a playground works fine. Setting it as type for a control placed on a UI does NOT work.
Does anybody have any clue what might be wrong?
Edit: Just to add that information: I checked the view using the new "Debug View Hierarchy" feature included in Xcode 6. Result: The control is definitely there.
I figured it out...
The problem was that I used the frame property of the super class instead of the dirtyRect parameter passed into the drawRect(...) method.
I just exchanged every access to frame with dirtyRect and now it works.
Looks a bit strange to me because (as far as I understand it) dirtyRect should refer to the same rectangle as frame.

Resources