Trying Affinity Designer

When I decided to make all my own art for Corgi Corral, I figured I would use Photoshop CS6 because that’s what I’m most familiar with. However, after making both the corgi and the sheep in Photoshop, I’ve started to realize that there’s a reason people use Illustrator for vector graphics: Photoshop’s tools just don’t cut it. I can’t afford Illustrator, so I went hunting for an alternative and stumbled upon Affinity Designer ($49.99), which happened to be on sale right before Christmas.

I just started messing with it the past few days, and I really like it. When you create a new document, there are preset sizes for Apple devices such as iPad Retina (1024×768 points) and iPhone 6 (375×667 points). All I had to do was watch a couple of short (< 4 minute) video tutorials before I felt like I knew enough to get started with the pen and shape tools, which are all really flexible. Another thing I like is that when you bring up the list of color palettes (PANTONE, Greys, Colors, Gradients, etc.), it also lists any custom palettes you’ve created from within Apple’s color picker. I’ve created a few palettes in Xcode, and I could access them easily from within Affinity Designer. Finally, I don’t have a graphics tablet, so the ability to do stuff like this is pretty great:

Anyway, the app gets great reviews and an iPad version is coming eventually, so if you’re looking for some intuitive, robust vector graphics or pixel art software, you might want to give Affinity Designer a try. It also has a nice dark interface, if that matters to you!

Getting Accelerometer Updates for Games

I’ve read pretty much every tutorial and Stack Overflow question involving accelerometer-controlled SpriteKit games and I’ve noticed that people often use the startAccelerometerUpdatesToQueue:withHandler: method to collect accelerometer data. However, there is another approach (which I use), which is to simply call startAccelerometerUpdates. Confused about the difference, I decided to hit the CMMotionManager class reference and found the following:

An app can take one of two approaches when receiving motion data, by handling it at specified update intervals or periodically sampling the motion data.

Is it just me or do those two things sound kinda the same? Anyway, moving on…under the second approach, “Periodic Sampling of Motion Data,” it says:

To handle motion data by periodic sampling, the app calls a “start” method taking no arguments and periodically accesses the motion data held by a property for a given type of motion data. This approach is the recommended approach for apps such as games. Handling accelerometer data in a block introduces additional overhead, and most game apps are interested only the latest sample of motion data when they render a frame.

(emphasis added)

I just wanted to point this out in case someone is thinking of making an accelerometer game and isn’t sure which method to use.

Herding Success

I finally found a decent fix for the GameplayKit/physics problem I’ve been fussing over for months (and that I wrote about yesterday). The good news is that it’s simple. The bad news is that it’s really only applicable to my particular game and probably won’t help anyone else that is looking for a way to get GKAgents to avoid the edges of the screen. Sorry! If it helps, I filed a radar about it.

Prior to figuring this out, I had just set my sheep to wander at a slow speed when they spawned. I set a low weight for the wandering goal because I mostly wanted them to flee from the corgi. I set the weight of each sheep’s fleeing goal high when the corgi approached, and back to zero when the corgi was farther away. I never changed the wandering goal.

The solution was to switch between the fleeing goal and the wandering goal, turning each completely on or off depending on the distance between sheep and corgi. I also assigned a higher weight to the wandering goal and increased the speed. Here’s the function that handles that logic:

func checkDistanceBetweenCorgiAndCritters() {
        enumerateChildNodesWithName("critter", usingBlock: { node, _ in
            let critter = node as! Critter
            let playerVector = CGPointMake(CGFloat(self.player.agent.position.x), CGFloat(self.player.agent.position.y))
            let critterVector = CGPointMake(CGFloat(critter.agent.position.x), CGFloat(critter.agent.position.y))
            let distance = self.distanceFromCGPoints(playerVector, b: critterVector)
            let maxDistance:CGFloat = 200.0
            
            if distance < maxDistance {
                critter.agent.behavior?.setWeight(100, forGoal: self.fleeGoal)
                critter.agent.behavior?.setWeight(0, forGoal: self.wanderGoal)
            } else {
                critter.agent.behavior?.setWeight(0, forGoal: self.fleeGoal)
                critter.agent.behavior?.setWeight(100, forGoal: self.wanderGoal)
            }
        })
    }

I call them critters instead of sheep so that I have some species-flexibility. ;) The above function borrows a method from Apple’s “AgentCatalog” demo project that calculates the distance between two positions. Now when the sheep get “stuck” along the edges, it’s only momentary because as soon as the corgi moves away, they’re super focused on wandering around.

https://www.youtube.com/watch?v=Grdr028WZFk

What’s Next
Here’s my short list of things to work on next:

  • Add some “flocking” behavior so the sheep tend to travel in cohesive groups.
  • Add a “run” animation for the corgi so it’s not just a legless blob.
  • Animate a little “+1” whenever a sheep enters the pen.
  • Add a pause menu with “resume” and “retry” options (and later an option to quit and return to the main menu).
  • Work on background art.

Spinning in Circles

I spent a long time messing with Corgi Corral yesterday. Too long, probably, because now I can hardly stand to look at it. I hear this is normal though, so I figured I’d take a break today and blog about it instead!

Awhile ago I wrote about the disconnect between GameplayKit’s agent system and SpriteKit’s physics world. I’m still working my way through these issues and have only managed to come up with partial, half-baked solutions. Specifically, I’m struggling with how to handle collisions between the sheep and the edge of the screen.

What Happens
When the sheep, who are part of the GameplayKit agent system, collide with the edges of the screen (an edge chain physics body), they “stick” to the edge and slide along it. Eventually, they all end up huddled against the edges of the screen.

What I’d Like to Happen
When the sheep collide with the edge of the screen, they should turn around and go the other direction.

My Failed Solution
I came up with something that almost works. When I detect a physics collision between the sheep and the edge chain, I run an SKAction that rotates the sheep in the other direction, like so:

sheep.runAction(SKAction.rotateByAngle(CGFloat(-M_PI), duration: 1))

That actually works really well in most cases. The sheep hit the edge of the screen, turn around, and go the other way. The problem is that when they hit the corners, or get pinned between the wall and other sheep, then they spin pretty much indefinitely, like so (tap/click to play the GIF, note bottom left corner):

spinning sheep

They currently have circular physics bodies, but I’ve tried a variety of other shapes and they still get caught in the Spin Cycle of Doom.

Why This Problem Even Exists
In essence, GameplayKit’s agent system and SpriteKit’s physics system are in constant conflict. In the “agentDidUpdate” method, the position of the sprite is always reset to match that of its agent after the agent carries out its goals for that frame. Therefore, the agent system essentially overrides the physics system. So what’s the point of giving sprites with GKAgents physics bodies at all? Well, mostly to prevent them from passing through other sprites and to be able to be notified of collisions.

What Now?
I have three hazy ideas for solutions, but I could really use some help. Here’s my thought process so far:

  1. Maybe there’s something I could do in the agent delegate methods? There’s got to be a use case for those besides just setting the position of the agent and the sprite.
  2. Another idea was that after rotating the sheep, I could apply an impulse to propel it away from the wall. The problem is, I need to know which direction to propel it, and I don’t know how to figure out which edge of the screen it hit. I’m also wondering if this could cause a similar problem with the sheep bouncing around the corners, unable to break out of the back-and-forth pattern.
  3. I could find some way to use the agent system itself to keep the sheep away from the walls. So far, adding the edge chain as an “obstacle” and ordering the agents to avoid it doesn’t work—I suspect because the edge chain is just a line instead of something with actual volume. I could add some large, clear rectangular sprites along (but mostly outside) the bounds of the screen and add those as obstacles maybe?

So yeah, I don’t know. The documentation on GameplayKit is still lacking and the dev forums are pretty much dead. I’m hoping this year’s WWDC will bring some clarity and new features to this otherwise nifty framework.

Got an idea for me? Tweet at me: @bhansmeyer.

Creating an Outlined Countdown Timer in SpriteKit with Swift

There’s a reason that most game developers don’t use Apple’s tools: they’re very limited. For instance, with UIKit, you can create a label and easily adjust its stroke color and stroke width. With SKLabelNodes in SpriteKit, those properties don’t exist. Therefore, it is (as of iOS 9 and Xcode 7.2) impossible to create an outlined SKLabelNode without doing some extra work.

I want my countdown timer in Corgi Corral to be white with a black outline. I combined two excellent tutorials to do this: Creating a Countdown Timer in SpriteKit with Swift and Outline Text in SpriteKit. Here’s the end result:

countdown timer with outline

In order to do this, you’ll need to use the great custom class ASAttributedLabelNode by Alex Studnicka. Just download the zip file from GitHub and copy the ASAttributedLabelNode.swift file into your project.

The timer tutorial has you create a custom subclass of SKLabelNode, adding several functions that compare dates and allow the label to update itself. I changed it to be a subclass of ASAttributedLabelNode instead and added two extra functions: one that formats the time as M:SS (single digit minutes and seconds) and one that sets the attributes of the string (stroke width, color, font, etc.). Here’s the full class:

class CountdownTimer: ASAttributedLabelNode {
    
    var endTime: NSDate!
    
    
    func update() {
        let remainingTime = timeLeft()
        attributedString = stringFromTimeInterval(remainingTime)
        
    }
    
    func startWithDuration(duration: NSTimeInterval) {
        let timeNow = NSDate()
        endTime = timeNow.dateByAddingTimeInterval(duration)
        
    }
    
    func hasFinished() -> Bool {
        
        return timeLeft() == 0
    }
    
    func createAttributedString(string: String) -> NSMutableAttributedString {
        let font =  UIFont(name: "Futura-Medium", size: 65)
        let textAttributes = [
            NSFontAttributeName : font!,
            // Note: SKColor.whiteColor().CGColor breaks this
            NSForegroundColorAttributeName: UIColor.whiteColor(),
            NSStrokeColorAttributeName: UIColor.blackColor(),
            // Note: Use negative value here if you want foreground color to show
            NSStrokeWidthAttributeName: -3
        ]
        return NSMutableAttributedString(string: string , attributes: textAttributes)
    }
    
    func stringFromTimeInterval(interval: NSTimeInterval) -> NSMutableAttributedString {
        let interval = Int(interval)
        let seconds = interval % 60
        let minutes = (interval / 60) % 60
        let timeString = String(format: "%01d:%02d", minutes, seconds)
        return createAttributedString(timeString)
    }
    
    private func timeLeft() -> NSTimeInterval {
        
        let now = NSDate()
        let remainingSeconds = endTime.timeIntervalSinceDate(now)
        return max(remainingSeconds, 0)
    }
}

Next, all you have to do is create a new CountdownTimer in your game’s scene class (by default it’s called GameScene.swift). Assuming your timer is named “timer”, whenever you want the timer to start, call timer.startWithDuration(seconds). In the scene’s update method, you can simply put timer.update().

Note: The end result of this is that you get an SKNode that you can do all sorts of SpriteKit-y things with. However, since it’s not actually an SKLabelNode, the vertical and horizontal alignment methods won’t work. You’ll have to position it like a regular node.

Obviously you can change the font to whatever you want, as well as the time format. And if you want to be able to have multiple timers with different attributes, you could always override the initializer to take a font name, size, color, etc. In fact, I might do that just to make it more flexible. Anyway, hope this helps somebody!

Is It Fun?

Over the past few days I’ve put in quite a bit of work on my first iOS game. I’ve tweaked physics, learned how to implement a timer, messed with GameplayKit, and continued to refactor my code so that it’s more clear and efficient.

Yesterday I realized that I hadn’t asked myself a very important question about the game: Is it fun? The answer, as the game currently stands, is no.

So then, the next logical question is: how can I make it fun? Before I attempt to answer that, let me tell you a bit about the game.

Introducing Corgi Corral

I’m planning to call it Corgi Corral. You play as a corgi and your goal is to herd a group of animals (starting with sheep) into their pen. The game is written in Swift, using SpriteKit, and at the moment is accelerometer-controlled. Here’s a very early screenshot:

corgicorral-dec2015

At the moment, the game doesn’t keep score and the sheep aren’t set to flee from the player (instead they just spawn in random positions at the beginning and wander aimlessly). I haven’t set up a lick of collision detection. The timer does nothing except count down. In other words: it’s not even close to being done. But I can already tell that it’s not fun. Funny, maybe, but not fun.

What makes a game fun?

I’m not going to get into Csíkszentmihályi’s theory of flow or the pros and cons of various game mechanics. And obviously, different people find different games fun. But for this game, specifically, I have some ideas.

Challenge. One of the problems with the game as it stands is that there’s not enough skill involved. The accelerometer controls can be a bit unpredictable as can the movements of the sheep, so it’s difficult to make decisions as a player that might improve your score. Therefore, tweaking the responsiveness of both the player and the sheep needs to be a priority. While some randomness in a game is okay, it’s frustrating as a player when you feel like you can’t change your technique to effect a better outcome.

Additionally, I’m torn as to what method of time-based gameplay to use. Should I set a time limit and count down, and see how many sheep the player can get safely into their pen in that amount of time? Or should I start at zero and count up, requiring the player to herd all the sheep into the pen and then awarding them a score based on how long it took? Feedback on that is welcome.

Personality. When I got the idea for Corgi Corral, I pictured it as a somewhat serious game. After all, corgis are actually herding dogs and this is something they used to do for a job. As I began working on the game, however, I changed my mind completely. I want the game to be zany and frantic and silly. I want it to make people laugh.

How can I achieve that? Having a time-based game already introduces an element of franticness, but I can do more. Music and sound effects will help. Some goofy physics and cute animations might also do the trick.

What if the corgi had a little cape? What if there were power ups? What if one level took place in SPACE? I don’t know. All I know is that I need to stay imaginative. After all, corgi-related games remain a mostly unexplored frontier. The possibilities are endless.

Progression. In other words: what makes players want to keep playing? At the moment, I don’t have a good, definitive answer to that. I know that I want Corgi Corral to be a game that people can play while waiting in line. However, I also want to introduce mechanics that make the game a little harder as time goes on. Perhaps there will be a minimum number of sheep that players must herd in order to unlock the next level. The next level might introduce ponds or fire pits or some way to lose sheep while also increasing the minimum number required to progress. Again, feedback and ideas are welcome.

Developing in the open

From this point forward, I plan to post a lot of code snippets and screenshots of the game’s progress. As a beginner, I feel that blogging about this experience (the good and the bad) will not only benefit other beginners but will help me learn as well.

I can’t say for certain how often I’ll post, and this whole idea might get tossed aside for awhile when my son is born (from what I hear, having a newborn can be a bit time-consuming!). I’ll do my best!

#DPP2015: Conclusion

Here are my final week and a half’s worth of photos for the December Photo Project! They’re all Live Photos processed into GIFs using Alive! and you can also look back at weeks One and Two. Oh, and I’ve set it so that GIFs don’t play automatically on this site (helps it load faster), so you’ll have to click on them to set them in motion.

Continue reading

Link

Apple Watch Revisited

Apple Watch Revisited

Nice post by Casey Liss that pretty much mirrors my thoughts and experiences with the watch. I also love my watch, and primarily use it for checking the time, weather, and notifications, as well as setting timers and making sure I stand up once in awhile. Nothing groundbreaking; just little improvements here and there. Also, it’s the most comfortable watch I’ve ever worn in my life, so it’s got that going for it as well.

Random Thought

I was just thinking about those weird rumors about a potential 15″ MacBook Air. Most Apple bloggers seem to think that the Air line will be phased out soon after being basically upstaged by the even slimmer 12″ MacBook.

I’m wondering: is it possible that the MacBook Air would essentially become the MacBook Pro instead? I’m guessing not, since the Pro has more ports and a discrete graphics card option and there’s no way to cram all that into a case as thin as the current Airs…right? What if Apple just had one laptop line called “MacBook” with 12, 14, and 16-inch screen sizes and upgrade options that would please Pro users?

Yeah I know, that probably won’t happen. But at this point, I’m so desperate for a laptop that I can use for development that’s as light as an Air and as powerful as a Pro that I’m willing to believe anything!

Favorite Christmas Albums

I’m a bit fussy about Christmas music. I tend to favor classical and jazz arrangements over pop, and while I’ve been to my fair share of Mannheim Steamroller concerts (and one Trans Siberian Orchestra concert), I wouldn’t rank their albums among my favorites. That being said, here are my top three favorites:

1. Christmas Adagios – Various Artists

I picked up Christmas Adagios at Barnes & Noble years ago and couldn’t convince anyone else that it was good because of the way the cover looked: like a sappy compilation of mediocre Christmas music. However, that couldn’t be farther from the truth. Featuring the likes of Pavarotti, the Choir of King’s College, the Vienna Philharmonic, and more—this is really the ideal classical Christmas album. If you’re looking for Christmas music that will create a solemn, sacred, reflective atmosphere: this is it. And with a whopping 45 tracks for only $11.99, it’s an absolute steal. It’s hard for me to pick a favorite track, but if I had to, I’d pick Pavarotti’s performance of “Ave Maria.” Gives me chills every time!

2. Jingle All The Way – Béla Fleck and the Flecktones

Quite possibly the strangest Christmas album I’ve ever heard, Jingle All the Way is a wild ride from start to finish. Béla Fleck is a world-reknowned banjo player, and yet I wouldn’t call this a bluegrass album. Instead it’s sort of a fusion of jazz and bluegrass that adds a bizarre yet fresh twist to a number of Christmas classics. Most of the tracks are purely instrumental, though a few feature Tuvan throat singing! My favorite tracks are “Sleigh Ride,” “Linus And Lucy,” and their great instrumental cover of Joni Mitchell’s “River.”

3. A Charlie Brown Christmas – Vince Guaraldi Trio

I don’t feel like this one needs a lot of explanation. I’ve been a Peanuts fan since I was a kid and nothing gets me in the holiday spirit like the soundtrack to A Charlie Brown Christmas!

Note: If you see big swaths of white space under the album names, those are supposed to be widgets where you can preview the songs. I don’t know how they’ll appear on various devices (or the RSS feed), so I thought I’d mention that.

Update: uBlock blocks the iTunes widgets, and I bet other ad blockers do too. Feel free to whitelist this site: I don’t have any actual advertisements on it.

Update #2: I removed the widgets because they were causing some strange behavior in Newsblur, which is my favorite RSS reader.

#DPP2015: Week One

I wasn’t originally going to post my December Photo Project pictures here, but changed my mind for two reasons. First, they’re Live Photos, which makes them slightly more interesting to Apple fans. Second, I’m hoping they’ll provide a little window into my life and help people get to know me a bit.

Without further ado, here’s Week 1:

December 1
Griffin the Weimaraner
This is Griffin, our Weimaraner. He’s my husband’s dog and he’s pretty much a big lovable dope.

December 2
Mac Classic II
This is the Mac Classic II that I picked up for $15 at a flea market a few years ago. It needs new capacitors, hence the checkerboard pattern. I don’t have the time to mess with that right now, so I may just send the logic board through the dishwasher again for a temporary fix! When I did get it to boot up, I found out that it used to belong to a dentist’s office…I think in Illinois somewhere. Fortunately they were smart enough to delete all the patient information off of it!

December 3
Hot chocolate with marshmallow
‘Tis the season for hot cocoa and marshmallows!

December 4
Moe the pig and Molly the calf
Our pet pig, Moe, and his buddy Molly, a calf that my husband rescued and bottle-fed after her mother died.

December 5
Doane Christmas Concert
Every year I go to the Christmas concert at Doane College, my undergraduate alma mater. The piece they were performing when I took this is an arrangement of Pavel Chesnokov’s “Salvation is Created” for choir and band. Here’s a recording of them closing the Christmas concert with the same piece in 2009. It’s one of my favorites, and I pretty much cry whenever I hear it.

December 6
Daisy the corgi
Daisy thinks she’s a cat and spends most of the day sitting either on the top of the couch or in the bay window itself.

December 7
Chocolate chip cookies
I made some chocolate chip cookies today and this my attempt to do a “flyover” of them. lol.

Again, all of these Live Photos were converted to GIFs using Alive!.

Link

Relay FM Memberships

Relay FM – Membership

With a few exceptions, most of my favorite podcasts are on the excellent Relay FM Network. Today Relay announced a membership program offering bonus content, a newsletter, and 15% off in their store. Although you can sign up to support the network in general, I decided to support one particular podcast that I’ve been enjoying, called Under the Radar by Marco Arment and [Underscore] David Smith. While I know Marco and David are more successful than I’ll probably ever be, I really like their show and want them to keep making it for a long time!