Create a Realistic Energy Drink Can to Present to Clients – Psd Premium Tutorial


Today, we have another Psd Premium tutorial exclusively available to Premium members. If you want to take your package design skills to the next level, then we have an awesome tutorial for you. Learn more after the jump!


This Premium Tutorial is Filled with Creative Tips

We have all been there before; how can we make our artwork look great when we are presenting to clients? The single easiest way to show something to a client is to show them in a way that they can understand. This tutorial will show you how to create a realistic energy drink in a way that you can demonstrate to your clients. Lets get started!


Professional and Detailed Instructions Inside

Premium members can Log in and Download! Otherwise, Join Now! Below are some sample images from this tutorial.


Psd Premium Membership

As you know, we run a premium membership system here that costs $9 a month (or $22 for 3 months!) which gives members access to the Source files for tutorials as well as periodic extra tutorials, like this one! You’ll also get access to Net Premium and Vector Premium, too. If you’re a Premium member, you can log in and download the tutorial. If you’re not a member, you can of course join today!

Deploy a Tank on a Mission in an Isometric War Zone

In this lesson we’re going to create a little tank moving application. The core of this particular tutorial is to make a tank aim at the the mouse pointer and drive towards a mouse click.


Final Result Preview

Let’s take a look at the final result we will be working towards:

Move the mouse to make the turret aim at it, and click anywhere to get the tank to drive to that point.

Step 1: Graphics Intro

Well, let’s get started.. For this tutorial we’ll need tank and turret graphics. I used Google SketchUp 7 to make mine.

First I created a tank as a whole. Then I turned the program’s view mode to “parallel projection”, positioning my camera at a 45° angle to the tank to make an illusion of isometrics in the game.

Please, don’t judge me for horrible graphics, I really can do much better but this is just for the sake of explanation :)

Then I hid the turret leaving only the tank body visible and rotated the body by 45° eight times, rendering each position separately. So I achieved 8 different views of the body. I did the same thing to the turret while the tank was hidden. I saved all 16 pics as PNG 24 with alpha channel. You can see the final result below. (This is not actually enough for this kind of movement, it would be better to have twice as many views of the tank but it’s enough for the purposes of this tutorial.)

.

You don’t necessarily need to use Google SketchUp of course, you may wanna use 3ds max or Maya or whatever you like, you may also use my graphics to practice if you don’t want to or cannot create your own graphics.

Step 2: New Flash Project

Now open up Flash (I use Adobe Flash CS4) and choose Create New Flash File (Actionscript 3.0). We will only need it to make a tank MovieClip and to connect the Game class to it later.

.

Step 3: Set the Document Properties

Right-click the stage and go to the Document Properties item. Make it 600 x 400 (or whatever you like) and 21 frames per second (this frame rate seems to be optimal to me so I almost always use it. It doesn’t really matter, though).

Click OK. Go to File > Save as and save this file as tank.fla in some folder on your computer (I recommend you create a Tank folder and put the file inside).

Step 4: Import Your Tank Images to Library

Now go to File > Import > Import to library. Find the folder where you saved your eight tank images, select them all and import to library.

.

Step 5: New Symbol

Create a new empty symbol by clicking this little icon in the library:

Choose MovieClip type and call the symbol “tank”. Put the registration point in the center (the registration point is that tiny black square in that grid of white squares, for those who don’t know).

Step 6: Edit the Symbol

After the symbol is created it appears in the library (its name “tank” is just a cosmetic name which is used solely in the library so it doesn’t matter what you call it). Open it by double-clicking its icon. Then take 1.png from the library and drag it onto the symbol’s stage. Align the image to the symbol’s registration point like in this screenshot:

You want the registration point to be in the center of the tank’s turning circle.

Step 7: Create Seven Blank Key Frames

Go to the symbol’s timeline. Rename the “Layer 1″ to “Tank”. Your tank’s body image (1.png) should be on the first frame of this layer. Click the second frame and without releasing your mouse button drag the cursor to the 8th frame selecting frames 2 through 8. Then right-click this selected area and choose “Convert to blank keyframes”.

Step 8: Drag All Images Onto the Stage

When 7 blank key frames are created, select the second frame and drag 2.png to it aligning the image with the registration point (just like you did with 1.png); imagining that the registration point is an axis that the tank will use to spin around when it’s turning. Do the same to the rest of the frames. You don’t have to align it very precisely, but the more precisely you align it the better the movement will look when the tank tries to follow the cursor as the game runs.

Step 9: Prevent the Timeline from Playing

After you dragged every image to the symbol’s stage and aligned them select the first frame and push F9 to open the actions panel. Type a single method “stop();” in it and close the panel. This is an important step because we don’t want our tank to automatically start spinning around as soon as it’s added to the stage.

Step 10: Create a Turret MovieClip

Go to the library and create a new MovieClip symbol. Call it turret. Double-click the symbol’s icon and do the same you did with the tank MovieClip (Steps 4 through 8) to the turret but using turret images. Align it to the registration point this way, at the point around which the turret would naturally turn:

Notice that I’ve named the turret images like this: 1-.png, 2-.png and so on, so that they wouldn’t replace the tank images when imported to library. You may want to use folders to put your images into. In this case your turret and tank images may have the same names.

Step 11: Assembling the Tank

After we’ve finished with turret symbol, open up the tank symbol again, create a new layer above the “Tank” layer and drag the turret movie clip from the library onto this layer. Align the turret with the tank body. The result should look like this:

Step 12: Give the Turret an Instance Name

Click once on the turret to select it (blue rectangle around it will indicate that it’s selected):

…then go to properties and give it and instance name mTurret (for MovieClip turret):

Click “Scene 1″ link to exit symbol editing mode.

Step 13: Export Your Tank for ActionScript

Right-click the tank symbol in the library, choose Properties (or Linkage if you’re using Flash CS3) from the dropdown menu (make sure you’re in an Advanced mode), check “Export for Actionscript”, and for the class’ name type in “Tank” (with capital T). This step will allow us to connect our Tank MovieClip to the instances created using our Tank class in future.

The graphics part is over for now; you may delete the tank from the stage. We’ll add it programmatically later.

Step 14: Create a New ActionScript File

In your Flash Authoring tool go to File > New and create a new ActionScript file.

Step 15: Save Your File

Go to the folder where you saved your tank.fla file and create a new folder called “main” inside. Save your ActionScript file in this folder as TankMaker.as. The location of this file should therefore be: tank/main/TankMaker.as

Step 16: Let’s Write Some Code

First of all, create a package and import the necessary classes into it:


package main {	

	import flash.display.*;
	import flash.events.*;

}

The word “main” here means the location of this file relative to our tank.fla

We will need “display” classes to show our assets on the screen and “events” to keep track of the mouse events.

Step 17: Public Class and Variables

Now we have to declare a public class TankMaker (according to the Actionscript file’s name) and the necessary variables:

package main {

	import flash.display.*;
	import flash.events.*;

	public class TankMaker extends Sprite {

		// the instance of our Tank class (which we exported for actionscript before)
		private var tank:Tank;

		// the vars to keep the coordinates of the point where we want our tank to move
		private var moveTankToX:Number;
		private var moveTankToY:Number;

		// coordinates of the point at which the tank aims its turret
		private var turnTurretToX:Number;
		private var turnTurretToY:Number;

		// current position of the tank
		private var currentTankPositionX:Number;
		private var currentTankPositionY:Number;

		private var tankSpeed:Number = 2;

		// the point at which the tank moves after a mouse click
		private var clickPoint:Object;

		// the angle of tank and turret rotation in radians
		private var Atan2:Number;
		private var turretAtan2:Number;
	}
}

I declared all of the variables as “private” because I don’t want them to be accessible from anywhere outside this class.

Step 18: Create a Constructor Method

Directly below the last variable create a public function and call it TankMaker. It’s going to be the constructor of the class. Then add an event listener for Event.ADDED_TO_STAGE to it so that we can create our tank object only after the stage is. Then pass this event to the method called addStage.

public function TankMaker() {

	addEventListener(Event.ADDED_TO_STAGE, addStage);

}

Step 19: Create a Tank Instance

After the stage is created and the ADDED_TO_STAGE event has triggered the addStage() method it’s about time to create a tank instance.

Declare a private function and call it addStage. The data type of the function will be: Event. And the return type will be “void” because we’re not going to return anything from it.

private function addStage (e:Event):void {

	//create a new tank instance of the movie clip
	// which you had exported for actionscript
	tank = new Tank();

	// now a little trick, I scaled my tank down
	// to the size of about one fourth of its original size
	// so that is wasn't so huge
	tank.scaleX = 0.25;
	tank.scaleY = 0.25;

	// set the initial position of the tank right
	// in the center of the stage
	tank.x = stage.stageWidth / 2;
	tank.y = stage.stageHeight / 2;
	// and add it to the display list
	addChild(tank);

	// now add event listeners for mouse down and mouse move
	// events to the stage
	stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownListener);
	stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveListener);

}

Step 20: Handling Mouse Movements

Create a private function mouseMoveListener() with a data type of mouse event to handle mouse movements across the stage. The event listener to trigger this function was created in the last Step.

private function mouseMoveListener(e:MouseEvent):void {

	// create a variable to keep the relative angle
	// between mouse's current position in degrees
	// and the tank's current position
	var angle:Number;

	// the next 2 variables are gonna be
	// equal to the the mouse's current position
	turnTurretToX = e.stageX;
	turnTurretToY = e.stageY;

	// calculate the relative angle in radians
	// between the mouse's curent position
	// and the tank's current position

	turretAtan2 = Math.atan2(turnTurretToY - currentTankPositionY, turnTurretToX - currentTankPositionX);

	// calculate the same angle in degrees.
	// to get degrees out of radians we have to
	// multiply radians by 180 and divide the result by PI
	// But here are some specifics of Flash
	// it calculates the angle not from 0 thru 360
	// but from 0 thru 180 and from - 180 thru 0

	// so let's add some conditional to get rid of this problem
	if (Math.round(turretAtan2 * 180 / Math.PI) < 0) {
		// if angle is between 0 and -180 add 360 to it
		angle = Math.round(turretAtan2 * 180 / Math.PI) + 360;
	} else {
		// if not, calculate it as usual
		angle = Math.round(turretAtan2 * 180 / Math.PI);
	}

	// having our angle value stored in a variable
	// let's rotate our turret towards the mouse pointer

	// I've done a lot of calculations trying to
	// figure it all out, so you may try to undestand my logic

	// I'm just picking the right frame of the turret MC depending
	// on the angle of the mouse from the turret

	if (angle > 240 && angle < 300) {
		// go inside the tank MovieClip then inside mTurret
		// go to the frame 1 and stop
		tank.mTurret.gotoAndStop(1);
	}
	if (angle > 300 && angle < 340) {
		tank.mTurret.gotoAndStop(2);
	}
	if ((angle >= 0 && angle < 20) || (angle > 340 && angle <= 360)) {
		tank.mTurret.gotoAndStop(3);
	}
	if (angle > 20 && angle < 60) {
		tank.mTurret.gotoAndStop(4);
	}
	if (angle > 60 && angle < 120) {
		tank.mTurret.gotoAndStop(5);
	}
	if (angle > 120 && angle < 160) {
		tank.mTurret.gotoAndStop(6);
	}
	if (angle > 160 && angle < 200) {
		tank.mTurret.gotoAndStop(7);;
	}
	if (angle > 200 && angle < 240) {
		tank.mTurret.gotoAndStop(8);
	} // end

}

Step 21: Mouse Click Handler

Below the end of our mouseMoveListener() function create a private function called mouseDownListener() with data type of MouseEvent and pass it to the moveTankOnEnterFrame method:

private function mouseDownListener(e:MouseEvent):void {

	// when click occurs assign the next variable
	// the coordinates of the mouse pointer's current position
	moveTankToX = e.stageX;
	moveTankToY = e.stageY;
	// and add event listener to move the tank frame by frame
	addEventListener(Event.ENTER_FRAME, moveTankOnEnterFrame);

}

Step 22: Move Tank Frame By Frame

Create a new private function called moveTankOnEnterFrame() and inside it call a method moveToCoordinates() with 3 parameters:

private function moveTankOnEnterFrame(e:Event) {
	moveToCoordinates(tank, moveTankToX, moveTankToY);
}

This will, eventually, cause the tank to drive towards the clicked point, every frame.

Step 23: Teach the Tank To Move

Now we have called moveToCoordinates() method but we haven’t created it yet. Let’s do that now.

The tX and tY won’t be used but we must create as many parameters as we called. This is how it looks:

private function moveToCoordinates(tank_mc:Tank, tX:Number, tY:Number) {

	// create a variable to keep the relative angle
	// between mouse's current position in degrees
	// and the tank's current position
	// this variable exists only inside this function so
	// you we can use the same name as we used before
	var angle:Number; 

	// calculate the angle (remember moveMouseListener?
	// we do the same here but with the tank itself)
	if (Math.round(Atan2 * 180 / Math.PI) < 0) {
		angle = Math.round(Atan2 * 180 / Math.PI) + 360;
	} else {
		angle = Math.round(Atan2 * 180 / Math.PI);
	}

	if (angle > 240 && angle < 300) {
		tank.gotoAndStop(1);
	}
	if (angle > 300 && angle < 340) {
		tank.gotoAndStop(2);
	}
	if ((angle >= 0 && angle < 20) || (angle > 340 && angle <= 360)) {
		tank.gotoAndStop(3);
	}
	if (angle > 20 && angle < 60) {
		tank.gotoAndStop(4);
	}
	if (angle > 60 && angle < 120) {
		tank.gotoAndStop(5);
	}
	if (angle > 120 && angle < 160) {
		tank.gotoAndStop(6);
	}
	if (angle > 160 && angle < 200) {
		tank.gotoAndStop(7);
	}
	if (angle > 200 && angle < 240) {
		tank.gotoAndStop(8);
	}

	// give the clickPoint a value of a current mouse position
	// when a click occurs
	clickPoint = {x:moveTankToX, y:moveTankToY};

	// calculate the angle in radians between the pointer's
	// current position and tank
	Atan2 = Math.atan2(clickPoint.y - tank_mc.y, clickPoint.x - tank_mc.x);

	// now add a value of Atan2 cosine to the tank's X position
	// and sine to its Y position every frame
	tank_mc.x += Math.cos(Atan2) * tankSpeed;
	tank_mc.y += Math.sin(Atan2) * tankSpeed;

	// now give the values to currentTankPositionX and
	// currentTankPositionY which we used in our mouseMoveListener
	currentTankPositionX = tank_mc.x;
	currentTankPositionY = tank_mc.y;

	// and finally a little trick. Since we don't want our tank to
	// start chaotically vibrating when it reaches its destination
	// we must calculate the distance between the tank's position and
	// the click point, and if it's less than 15, remove the ENTER_FRAME listener
	if (Math.abs(tank_mc.x - clickPoint.x) < 15 && Math.abs(tank_mc.y - clickPoint.y) < 15) {
		removeEventListener(Event.ENTER_FRAME,moveTankOnEnterFrame);
	}
}

Why use a distance of 15? Well, I found out that it never goes beyond 15 by simply tracing it like this:

trace(Math.abs(tank_mc.x - clickPoint.x));

…you can do the same if you want ;)

Step 24: Overviewing The Whole Class

As our class is ready, let’s take a look at it as a whole:

package main {

	import flash.display.*;
	import flash.events.*;

	public class TankMaker extends Sprite {

		private var tank:Tank;

		private var moveTankToX:Number;
		private var moveTankToY:Number;

		private var turnTurretToX:Number;
		private var turnTurretToY:Number;
		private var currentTankPositionX:Number;
		private var currentTankPositionY:Number;

		private var tankSpeed:Number = 2;

		private var clickPoint:Object;

		private var Atan2:Number;
		private var turretAtan2:Number;

		public function TankMaker() {

			addEventListener(Event.ADDED_TO_STAGE, addStage);

		}

		private function addStage (e:Event):void {

			tank = new Tank();
			tank.scaleX = 0.25;
			tank.scaleY = 0.25;
			tank.x = stage.stageWidth / 2;
			tank.y = stage.stageHeight / 2;
			addChild(tank);

			stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownListener);
			stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveListener);

		}

		private function mouseMoveListener(e:MouseEvent):void {

			var angle:Number;

			turnTurretToX = e.stageX;
			turnTurretToY = e.stageY;

			turretAtan2 = Math.atan2(turnTurretToY - currentTankPositionY, turnTurretToX - currentTankPositionX);

			if (Math.round(turretAtan2 * 180 / Math.PI) < 0) {
				angle = Math.round(turretAtan2 * 180 / Math.PI) + 360;
			} else {
				angle = Math.round(turretAtan2 * 180 / Math.PI);
			}

			if (angle > 240 && angle < 300) {
				tank.mTurret.gotoAndStop(1);
			}
			if (angle > 300 && angle < 340) {
				tank.mTurret.gotoAndStop(2);
			}
			if ((angle >= 0 && angle < 20) || (angle > 340 && angle <= 360)) {
				tank.mTurret.gotoAndStop(3);
			}
			if (angle > 20 && angle < 60) {
				tank.mTurret.gotoAndStop(4);
			}
			if (angle > 60 && angle < 120) {
				tank.mTurret.gotoAndStop(5);
			}
			if (angle > 120 && angle < 160) {
				tank.mTurret.gotoAndStop(6);
			}
			if (angle > 160 && angle < 200) {
				tank.mTurret.gotoAndStop(7);;
			}
			if (angle > 200 && angle < 240) {
				tank.mTurret.gotoAndStop(8);
			} 

		}

		private function mouseDownListener(e:MouseEvent):void {

			moveTankToX = e.stageX;
			moveTankToY = e.stageY;
			addEventListener(Event.ENTER_FRAME,moveTankOnEnterFrame);

		}

		private function moveTankOnEnterFrame(e:Event) {

			moveToCoordinates(tank, moveTankToX, moveTankToY);
		}

		private function moveToCoordinates(tank_mc:Tank, tX:Number, tY:Number) {

			var angle:Number; 

			if (Math.round(Atan2 * 180 / Math.PI) < 0) {
				angle = Math.round(Atan2 * 180 / Math.PI) + 360;
			} else {
				angle = Math.round(Atan2 * 180 / Math.PI);
			}

			if (angle > 240 && angle < 300) {
				tank.gotoAndStop(1);
			}
			if (angle > 300 && angle < 340) {
				tank.gotoAndStop(2);
			}
			if ((angle >= 0 && angle < 20) || (angle > 340 && angle <= 360)) {
				tank.gotoAndStop(3);
			}
			if (angle > 20 && angle < 60) {
				tank.gotoAndStop(4);
			}
			if (angle > 60 && angle < 120) {
				tank.gotoAndStop(5);
			}
			if (angle > 120 && angle < 160) {
				tank.gotoAndStop(6);
			}
			if (angle > 160 && angle < 200) {
				tank.gotoAndStop(7);
			}
			if (angle > 200 && angle < 240) {
				tank.gotoAndStop(8);
			}

			clickPoint = {x:moveTankToX, y:moveTankToY};
			Atan2 = Math.atan2(clickPoint.y - tank_mc.y, clickPoint.x - tank_mc.x);

			tank_mc.x += Math.cos(Atan2) * tankSpeed;
			tank_mc.y += Math.sin(Atan2) * tankSpeed;

			currentTankPositionX = tank_mc.x;
			currentTankPositionY = tank_mc.y;

			if (Math.abs(tank_mc.x - clickPoint.x) < 15 && Math.abs(tank_mc.y - clickPoint.y) < 15) {

				removeEventListener(Event.ENTER_FRAME,moveTankOnEnterFrame);
			}
		}
	}
}

Step 25: Final Strokes

Go to File > New, and create a new ActionScript file. Save it as “Game.as” in the same folder as your tank.fla file. This will be our document class.

Here’s the code for Game.as class:

package {

	import flash.display.*;
    // import the contents of our main folder
	import main.*;

	public class Game extends MovieClip {

		private var newTank:TankMaker;

		public function Game () {

            // create a new instance of our tank maker class
			newTank = new TankMaker();
            // and add it to the stage of course
			addChild(newTank);
		}
	}
}

Save the file. All it does is create a tank and add it to the main stage, ready to control.

Step 26: Attach Game Class to the FLA

Open up tank.fla and go to the Properties panel. For Class type in “Game” and save the file.

Aha! There we go. You can now press CTRL + ENTER on PC (CMD + RETURN on Mac) and test the Game.

I hope you enjoyed this tutorial, thanks for reading :)

Friday Photo Critique #36

Friday Photo Critique is our weekly community project, where we publish a photograph submitted by one of our wonderful readers, then ask you all to offer constructive feedback on the image. It’s a great way to learn more about photography, express your viewpoint, and have your own image critiqued!


Quick Ground Rules

  1. Play nice! We’ve deliberately chosen photographs that aren’t perfect, so please be constructive with any criticism.
  2. Feel free to offer any type of advice – composition, lighting, post-processing etc.
  3. You can also link to photographs that you feel offer a great example of this type of image shot exceptionally well.

Without further ado, here is this week’s candidate for Friday Photo Critique!


The Photograph

Photo Critique

Photographer: Marc Thoni

Please let us know what you think in the comments – how would you have approached the scene or taken the photo differently? A massive thank you to everyone who commented last week.

The most constructive and helpful comments will be featured on the site, and you’ll also be given priority to feature your own work in a future Friday Photo Critique!.

How to Find More Hours in the Day

We’ve all wished for more than 24 hours in a day, but short of developing the powers to bend the laws of space and time, that’s not going to happen. But one thing we can do is bend the ways we use the hours at our disposal. If you look hard enough, you can discover time you didn’t know you had.

Shift Your Day

When I decided I needed to find dedicated time to work on a writing project, I started setting my alarm 45 minutes earlier. Of course, I also have my bedroom clock set to run a half hour ahead. So, 7 a.m. became 6:15 a.m. … which is actually 5:45 a.m. I allow myself until 6:30 a.m. for breakfast and Internet browsing, but then it’s work time. I love working in the early morning: it’s a quiet, thoughtful time of day. Not a morning person? I think it would be harder to shift on the evening side, since evenings often fall prey to social plans, errands or exhaustion. But if you can, more power to you.

Save Time, Save The Planet

Commuting by public transit provides a great opportunity to both get where you’re going and get things done, sparing the environment your automobile emissions in the process. Increasingly, cellular networks are available on below-ground public transit, and wi-fi is available on some commuter trains. No Internet access? Work offline or just bring a book or legal pad. If it’s a particularly long commute, try convincing your boss that the work you get done in transit should merit a shorter in-office workday.

Go Mobile

If you need to read a book that would help you do your job better, find the audio version and listen to it while commuting to work, exercising or walking the dog. Same goes for podcasts. Need to plan for a meeting or a project? Grab an audio recorder and dictate your thoughts for an intern or assistant to transcribe later. Or if you have an Evernote account that you can share access to, record your thoughts to Evernote and text your assistant when you’re done. You can have an outline on your desk by the time you arrive at the office.

Block Your Meetings

You could write a book about how to make meetings more efficient, but let’s just look at scheduling for now. I find that when meetings are spread sporadically across the week, particularly at block-slicing times like 10 a.m. or 2 p.m., it’s hard for me to get important things done. If possible, try blocking your meetings together. If you know Monday afternoons, Wednesday afternoons and Thursday mornings are dedicated to meetings, you can block and structure the remaining time during your workweek to get projects done. Aim for at least two full, free days per week.

Break Free from TV

Watching a favorite television show is a great way to relax, but tethering yourself to an 8 p.m. program on Wednesday nights might kill any chances of productivity by slicing up your evening block of time. DVR your favorite shows and have them queued up for when you’ve set aside a block of time to unwind. Don’t have DVR? Wait for them to come out on Netflix, so you can order or stream them at your leisure.

Self-Evaluation

We get so caught up in the day-to-day of our established routines that we often don’t think about everything that we’re doing. We’re simply doing it because we always have. Take a typical week and log every activity and how much time you spend doing each. Then sit down and evaluate. Are you surprised how much time you spend doing things like shopping, cleaning or maybe nothing at all? If your time is valuable to you, are you will to invest in a shopping or cleaning service? Can you better structure your open time so you can fit in both relaxation and productive tasks? When it comes to evaluating how you use your time on the computer, a service like Rescue Time can help.

Turn Waiting into Doing

If you know you’ll be someplace where you will likely have to endure a wait, such as the doctor’s office or the RMV, bring along a couple of portable tasks. It could be an article to read, a notepad to jot down some thoughts or a calendar to plan the week ahead. Waiting can eat up nuggets of time that if you don’t plan ahead can go idle and wasted, but with a little planning they can be recovered and maximized.

Having More = Getting More

These are just a few of the ways you can take control of the clock – as opposed to the clock controlling you.  This great blog post by entrepreneur Jun Loayza details more time-recovering habits worth cultivating.

Remember, the sooner you get started on finding more hours in your day just to get things accomplished, the sooner you’ll find you have more hours in your day that you can have just to enjoy.

How to Simulate a Torn Flag Animation using 3ds Max and After Effects – Day 2

In this 3ds Max tutorial you will learn how to generate a torn flag animation using cloth simulation, and also how to combine all of the elements, such as the flag, debris, and dust, in order to create to the final scene in After Effects.

This tutorial is Day 2 in a series – Go to Day 1.


Video 1

Download

Note: click the ‘Monitor’ icon to view tutorial in full-screen HD.


This tutorial is Day 2 in a series – Go to Day 1.


Don’t miss more CG tutorials and guides, published daily – subscribe to Cgtuts+ by RSS.

Beautiful Custom Bokeh With the Bokeh Masters Kit

Today we’ll be reviewing a product called The Bokeh Master’s Kit. We’ll tell go through what it is, how to use it, and whether or not you should consider adding it to your arsenal of photography tools.


What is Bokeh?

Before we go into what the product does, you should understand the concept of bokeh. When you have a lens that is of ample quality to produce a relatively shallow depth-of-field, the background becomes extremely blurry when the foreground is in focus (and vice-versa).

Because of a whole lot of complex physics (aka. spherical aberration) and the way light is fed through the lens, out of focus points of light essentially take on the shape of your aperture. In most cameras, this produces a round or near-round (sometimes slightly octagonal) shape representing the points of light in the distance.

Though the lens and aperture are distorting the true image, the result is something quite beautiful and is generally regarded as a positive feature of an image.

The image above is a perfect example of how bokeh can add significant aesthetic value to an image (image source). Keep in mind that this image was taken at f/2.2. If your lens doesn’t go below f/4 or so, you might have a hard time producing a good bokeh.


The Bokeh Master’s Kit

What the Bokeh Master’s Kit does is change the shape of the bokeh in an image by filtering the light through a custom-shaped hole on the front of your lens.

As you can see in this sample image from the kit’s website, the results can be quite fun and unique. So how does it do this exactly? Let’s take a look.


What You Get

To give you a good idea of what you’ll get in the kit, here are a couple of pictures that I took when I first received mine.

As you can see, you get five plastic sheets containing pieces to punch out. The red sheet is a little box that you fold up to hold your disks, and the rest are disks containing different shapes to mold the bokeh along with the holder piece that is placed over the camera.

Here’s a more comprehensive list of everything included:


How To Use It

To use the kit, simply place one of the disks in the holder, place the holder over the front of your lens and use the included rubber band to strap it on.

The tricky part is that you can’t just take a picture of anything. You have to create a setup like the asian doll picture above where a good bokeh is already being produced. Remember that the kit modifies bokeh, it doesn’t create it!


My Experience

When I first received the Bokeh Master’s Kit, I was a little hesitant to attach it to my lens with the rubber band. Sure enough, when I tried it, the rig in combination with an autofocus lens (and therefore a moving lens) seemed to be a bad combination as it was wearing on the gears a bit.

Turning the autofocus off was an easy solution, but then you’re forced to manually focus and my focus dial is unfortunately near the front of my lens, which was obstructed by the bokeh kit. In the end I found it to be easy enough to place a disk in the holder and then just hold it in front of my lens while I shot.

However, I think the disk holder would be much better if it were actually a lens attachment similar to a modified polarizer or lens cap. This would really increase both manufacturing costs and the end customer price, but the improved setup would be worth it.

Moving on to usage, I first tried the kit with a low grade Canon 18-55mm F/3.5-5.6 lens. Unfortunately, the results with this lens were quite fickle. Though I could fairly easily produce a decent bokeh, it was really tricky to get the kit to reshape it in any way. Despite the fact that I was trying to produce a star, I kept getting Pac Man shapes!

Success

Faced with failure on my cheap kit lens, I decided to get more serious and pulled out a Canon f/2.8 lens. To setup the shot, I grabbed a few studio lights, set a toy catapult on a pool table, and placed a pile of Christmas lights in the background. Here’s what I came up with straight from the camera.

Just to give you a good idea of what’s going on here, the settings are as follows: 1/15 sec exposure (with flash and tripod), f/3.2, 100mm. As you can see, the bokeh is coming through quite nicely.

This time, equipped with a decent lens and a better setup, the effect of the bokeh kit was instant and required zero fiddling with settings or adjustments. In fact, the results were excellent!

Placing the bokeh kit over the lens considerably darkens the image but as long as you adjust your settings accordingly it’s not a problem. Also, it places a dark vignette around the edge of the photo. Some photographers might find this annoying but I was loving the effect on this particular setup.

Though I was frustrated with the results from the cheaper lens, once I had the right setup I found the kit to be a blast to use. It’s an admittedly cheesy effect but it’s something you can’t normally achieve and is really neat to have on hand for certain occasions.

Here are a few more images from the same shoot:


Closing Thoughts

So should you get one? I vote yes. It’s currently only $25, which you’ll earn back in positive comments from your friends and family wondering how the heck you achieved the amazing effect. The best application I can think of is for children’s portraiture. The fun shapes really lend themselves to kid photography and you’ll no doubt snag a few clients with the originality of the images.

Before you purchase anything, just remember my advice about making sure your lens is up to par and also that it’s probably a good idea to turn off auto-focus prior to attaching the kit to your lens.

For all you do-it-yourselfers out there, the effect is actually pretty easy to achieve on your own. Check out this guide from DIY Photography or run a search on Flickr for “custom bokeh” to see what others have come up with.

Use the comment section below to let us know what you think of the product and whether or not you’ll be ordering one. Also be sure to let us know if there are any other products you’ve been considering purchasing that you’d like us to review.

What Would You Do If You Were Let Go?

The economic situation is tough right now; it really hasn’t eased up much recently nor does it show signs of doing so anytime soon.  No matter how productive you may be at what you do, you may find yourself out of work if the proverbial “house of cards” at your place of employment comes tumbling down.

If that was to happen, are you prepared?  Regardless of how you feel your position stands in terms of security, you just never know – so it’s good to make sure you’re ready should the need arise.

But let’s take it one step further.

If your job was to disappear tomorrow, are you prepared to do something else instead?

What would you do if you were let go?  Would you simply move on, or re-create your work like in some form or another?  Would you go it alone?  Let us know in the comments.

Keeping Track of Your Tech Devices

Yesterday I realized that I had 5 portable devices to recharge and a drawer of tangled cables from which to get each of the 5 recharge cables (each device has its own).  My TV remote and cordless phone seemed to need new batteries and the hand held vacuum was out of charge, too.  It took me a good half hour to get everything all set and plugged in, by which time the cables were starting to tangle again.  It’s like I was having a close encounter with clutter of a third kind – a technological kind.

How does everyone handle their technology maintenance?  Do you have a routine?  Have you found a way to keep devices, cables and batteries organized without spending too much time on it?

Chomp Out Your Own Pac Man Animation – Part 2

This 2 part tutorial is a simulated Pac Man animation as he navigates a maze and gobbles dots along the way… with ghost chasers. The tutorial will include guidelines on building the components in Photoshop or Illustrator and then integrating them into AE to animate Pac Man. This is more of a design project that incorporates many of the foundational skills associated with AE; pre-comps, transformations, layer masks, etc.


Tutorial

In this project we will expand upon the Pacman animation we completed in Part 1.
What we will be doing in part 2:

1. Design the ghost shape and eyes, and animate them in After Effects
2. Add a "Start Game" and "Game Over" Slate
3. Add some Start Game and End Game audio
4. Add some enhanced sized muchies
5.
Add some enhanced Munchie audo
6. Navigate our ghost in th maze, annimating changes in color

What you will need to complete Part 2

1. All of the footage files associated with Part 1. You can access these files at http://ae.tutsplus.com/
2. Download all the footage files associate with this tutorial; Part 2.

The Basic Ghost Design –
Preparing the Files in Photoshop

Ghost

The ghost element is easily created in Photo Shop or Illustrator. My tutorial uses Photoshop as the design tool.

Launch Photo Shop and open a new document.

Use a measurement that conforms to your needs. 300×300 will do nicely.

Use a transparent background.

(You only need one ghost. We’ll duplicate it later in After Effects.) I recommend you use the same dimensions as you did for your PACMAN image.

Ghost Body

1. Draw a square with the Marquis tool. Use most of the available space in your art board. Fill it with any primary color; red, green, blue, yellow.


2. Create a new layer and draw a sphere the same width as the square, and fill it with the same color as your square, then arrange the layers so they form the shape of a PACMAN Ghost.

Merge the layers.

3. Use a semi-round brush the size you want to make the eye sockets, and paint two spots where you want the eyes. I opened the Brush palette in Photoshop and changed the shape dynamics of a basic round brush to create an oval shaped brush. If you use the grid view in Photoshop it will make your life easier with this task.


Ghost Eyes

1. Create a new layer and draw a round circle with the Marquis Tool that will fit inside the eye sockets of your ghost body and fill it with black or white; something that will contrast with the body of your ghost. Rename your layer as ghost body.

2. Duplicate the layer and arrange the eyes symmetrically – to fit inside the eye sockets, and merge the two eye layers. Rename the layer as eyes.

At the end of step 2 here, you should have two layers in your photoshop document. a Ghost image and eyes.


You’re done with this design element. Be sure to save your file as something other than untitled. My suggestion is to call it Ghost Layers. Open After Effects and import this file as a Composition.

 

Enhancing The Basic Pac Man Simulation

Open your Simulated Pacman Part 1 AE project file. Imort the footage files for Part 2

Looking at your completed Part 1, you should have at the very minimum, the following functional layers, and in this order from top to bottom, in your timeline:
PacMan – as a composition.
Munchies … I call mine dots.
Maze
PacMan audio … mine is called munchie clip.

Critical Audio Clip Placement

The first thing we’re going to do is put in our Audio clips for the start of the game and the end of the game. It is critical we do this first because it sets up the parameters for how Pacman and the Ghosts will ultimately interact on the screen.

1. FROM THE PROJECT WINDOW – Drag the Intro to Pacman audio wav file into the timeline two times.

2.Position the clips so the beginninig of one of the clips aligns at the begining of the timeline, and the other aligns with the end of your timeline.

3. In preparation for the next step, we need to position the timeline marker at then of the introduction music.

Modifying Pac Man’s Chomping

Now we’re going to adjust PacMan’s two frame animation so that he starts chomping at the end of the introduction music, instead of right away.

1. Double click on the Pacman Comp in the TIMELINE window. This will open a new Comp Window and a new Tab in the Timeline.

2. Double Click on the layer. This will open a new comp Window and a new Comp Tab in the Timeline. Yes, I know I’m repeating myself. :-)

You should now be looking at your origninal two layer Pacman comp, as illustrated above.

3. Now select the three Rotation key frames in each layer and drag them so that the first key frames line up with the timeline marker. The easiest way to select the key frames is to draw a box around one set of key frames, hold the shift key and draw a box around the next set.

Modifying Pac Man’s Route

1. In Part 1 I had my Pacman navigate off-screen to end the timeline. Seemed like a natural thing to do … But in this scenario, we have Ghosts with which to contend, so we want to change up the route that Pacman takes … one that ultimate leads to his demise. Ya ha ha ha ha. To do this we need to go in reverse for a moment and back out of some of our hard work in Part 1. Not to worry, we’re going to put everything back to normal. So … Select the Pacman layer in the Timeline. Tap the P key to reveal the Position Key Frames for the Layer, then click on the Positon text to select all of the Key Frames. Your layer should like the illustration below if done correctly.

2, Now, in the command bar, choose Animation > Key Frame Interpolation > and change the Roving Setting to Lock to Time, then click OK.

3. Now hold the Ctl Key (Cmnd Key on the Mac) and select one of the key frames. All your key frames should now be diamond shaped. Then select off the layer to deselect the key frames.

Now comes the tricky part. You must determine at what point in Pacman’s route you want him to alter his course. In my Part 1 maze, Pac man takes a northbound turn right at 14 seconds, but at that point, my Pacman should be dying. So this would be a good place to put in our pacman ending audio. Don’t worry we’ll come back to the Position Key Frames.

4. Drag the "Pacman Ending.mov" from the Project Window into the Timeline. You should position it so the end of the clip lines up with the first frame of the ending music. See my illustration below.

Hold down your control key and drag the timeline marker over the pacman ending clip to get an idea of where you might want to trim it.

Okay, back to those key frames. So now I know the exact point in time Pacman expires, so my last position keyframe will correspond with that point … dictated by the audio.

5. Manipulate your position Key Frames so that your last keyframe corresponds with the first frame of the "padman ending.mov clip.

Compare the two illustrations below to get an idea of what I did to alter my position Key Frames.

Okay … some more tweaking to do here. Those rotation Key Frames need to be corrected, but first we need to make our Position Key Frames Rove across time.

6. Select all the Position Key Frames in the Pacman layer. In the command bar choose Animation>Keyframe Interpolation>Roving>Rove Across Time. Click OK.

7. Tap the U key on the Pacman layer to reveal both the Position and Rotation Key Frames, and then line up the Rotation Keyframe pairs with their corresponding Position Keyframes. My illustrations below show out-of-synch Rotation Key Frames and then in-synch Key Frames.

Okay, we’re done with Pacman for the moment. Now we can concentrate on the Ghosts, and their interaction in the maze.

Animating the Ghost Eyes

Making the eyes wiggle in the sockets of our ghost is similar to the rotation animation we accomplished with Pacman in Part 1. We will use three key frames and the “loop out” expression.

1. Double Click on the Ghost comp. You should see two layers in your timeline; the ghost body and the eyes.

2. We only need to concern ourselves with the eyes layer, so select the eyes layer and tap the P key on the keyboard. This will reveal the Position transformation properties. Move your timeline marker to the end of the introduction music (about 4 seconds) in the timelilne then click on the stopwatch next to the Position property indicator. You will notice that a key frame appears on the timeline. Immediately Copy this keyframe.

3. Advance the timeline marker 3 frames, by tapping the Page-Down key three times. In the Comp Window move the eyes layer to the position you wish for them to toggle.

 

4. Advance the timeline marker three frames as in step three, then Perform a Paste function to create a new key frame at the new timeline position.

 

5. Hold the Alt Key (Command for Mac) and click on the stop watch to enable expressions for the layer. Select all three key frames and then from the expressions language menu choose Property > loopOut(type = "cycle", numKeyframes = 0) from the expression language arrow.

6. Precompose the two layers by selecting both layers and choosing Precompose from the Layer Menu. (Layer>precompose) Name your pre composition appropriately. You may need to find it later. Now you have one layer of a ghost with animating eyes. This is the layer we will move into our working comp.

Ghost Treak

In this tutorial we will deal with two Ghosts:

1) A Death Ghost; the one who ends Pacman’s journey, and

2) A Munch Ghost; a Ghost that gets eaten by Pacman.

Some of the steps here will be familiar to you if you completed Part 1.

1. Drag your Ghost Composition into the Composition Window, resize it and position it where you wish for it to start in the maze.

2. Duplicate the Ghost Composition Layer: Select it, Edit>Duplicate. and move it to a position in the maze where you want it to start.

3. Now change the color of one of your Ghosts. Select one of the Ghost layers then Access the Effects Menu from the command bar … choose Color Correction>Change to Color.

4. Using the Eye Dropper choose the color you want to change by clicking on one of your Ghosts.

5. Change the color of your Ghost by changing the value of the Hue Transformation Propery.

We will come back to the Effect Palette in a future step to animate the color of your Ghosts.

Ready To Navigate

1. Choose one of your Ghost layers and tap the P key to reaveal the Position properties. Move the timeline marker to the end of the introduction music, then enable Position animation for this layer by clicking on the stopwatch. You will see a diamond show up in the layer.

2. Advance the timeline marker 20 or 30 frames, then move your Ghost in the comp window to a new position. (Hold down the shift key to move in a straight line.)

 

3. You will have the same bezier path issue with your Ghosts as you did with Pacman. So use the Convert Vortex Tool to square-up the Ghost path in the Maze.

4. Repeat steps 1 through 3, navigating your Ghost around the maze. If this is the "Death Ghost" you will need to cooridinate your Ghost to collide with PacMan at the start of the "Pac Man dies" music. If this is the Munchie Ghost, you will need to coordinate the Ghost to collide with Pacman prior to the "Pacman dies" audio.

Remember to use the Key Frame Interpolation feature to force each of your Ghost Position Key Frames to Rove Across Time. Select all of the position Key Frames for the layer and then from the command bar choose: Animation>Keyframe Interpolation>Roving>Rove Across Time. Click OK. (Click here if you need help.)

Tweaking The Munch Ghost

1. Your munch Ghost needs to disappear at the point that Pacman and the Ghost collide.
To make this happen simply trim that Ghost Layer back to the point where Pacman and the Ghost Collide.

2. While we’re here we might as well add the "Ghost Eat" Audio in the timeline. Position your timeline near the point of collision between Pacman and Munch Ghost. Drag the "Ghost Each" Audio into the timeline.

3. Use the RAM Preview button in the Preview Tab or Hit the 0 in the numeric keypad to review the animation.

 

Tweaking Pacman At The Collision of the Death Ghost

1. Pacman needs to disappear at the point at which Pacman and the Death Ghost collide.
To make this happen simply trim the Pacman layer back to the point where Pacman and the Death Ghost Collide. This point also corresponds with the "Pacman dies.mov" We placed this audio in the timelne in an earlier step … referenced here.

2. Tweak your layers and Key Frames in the Timeline to line everything up. You won’t get it right the first time … trust me.

Mega Munchies

In the original Pacman Video Game, the player navigated Pacman around the maze to eat dots and Mega Munchies in order to earn points and change the Ghosts into edible Ghosts instead of Death Ghosts.

In my version, my Mega Munchies are nothing more than Big Dots. To make my dots I simply added shaped layers, positioned them in the comp window at desired locations, and then performed a precomp to collapse the shaped layers into one layer.

1. Create a new shaped layer: Go to the Command bar and choose Layer>New>Shape Layer.

2. Now, in the tool bar choose the Elipse tool, and modify the properites associated with the layer.

3. In the comp window, draw a sphere and position it in the maze accordingly.
(You can duplicate the layer to create as many Mega Munchies that you want.)

4. Position the shape layers in the maze to your liking.

6. Trim the appropriate Shape Layer(s) to correspond with the point that
Pacman
"eats" each Mega Munchy.

In my version Pacman only has time to munch one.

7. From the Project Window, drag the Cherry Bite.wav audio file to the timeline .. lining it up with where Pacman eats the Mega Munchy.

8. (Optional) Select all of your shape layers and create a precomp.
You can reference how to do that by clicking here. What this does is save you some real estate in your timeline.

Animating the Ghost Color Changes

In the original Pacman Video Game, whenever Pacman consumed a Mega Munchy .. in some versions it was a piece of fruit like a Cherry or Strawberry… all of the active Ghosts turned blue for a limited amount of time. If Pacman ate a Blue Ghost the player earned points, but if perchance Pacman encountered a Ghost of a different color, the game ended. So what we’re going to do now is animate those Ghosts in out timeline so they turn blue, and then back to their original colors, just in time to end our game at the end of our timeline.

1. In the Timeline Window, move the timeline marker to the point at which Pacman eats the first Mega Munchy. For an additional point of reference, this is also where we placed our Cherry Bite.wave file.

2. Select all Ghost layers, and access the Effects Control Palette. Click on the Hue Transform Stopwatch to set a keyframe.

3. Advance the timeline marker one frame, and change the Hue transform value till the Ghosts turn Blue. You will see that a new Key Frame was created for each of your Ghost layers. It will be necessarry to copy each pair of these keyframes for each of your Ghost layers that do not get eaten by Pacman during the time the Ghosts are Blue.

4. Advance the timeline marker to the point at which Pacman eats the first Blue Ghost, and then from the Project Window, drag into the Timeline the "Ghost Eat.wav file, and align it with the timeline marker.

One Ghost down … one to go.

5. Advance the timeline a couple of seconds .. at least past the point where Pacman eats the first Blue Ghost. Select one of your remaining Ghosts .. If you haven’t already done so, Copy the Hue Transform Key Frames for this layer that you created in step 3. Paste them into the layer, then swap the order of these Key Frames in the timeline.

Now you have returned the Ghost to it’s original color.

FINISHING UP

If we’ve done everything right most of our animating is done, but there is still one more little item with which to attend. You may notice in my maze there is a small line at the top of the Ghost box before they start animating. Let’s call it the Gate.

At the point the Ghosts are released, the Gate goes away. I did this by using a layer mask on the Maze layer.

Masking Out The Gate

1. Select your Maze layer in the Timeline Window, position your timeline marker to the point just prior to when the Ghosts start moving around the maze.

2. Using the Pen Tool from the tool bar, draw a box adjacent to the Gate.

3. Tap the M Key to reveal the Mask properites for the layer, and then click on the stopwatch.
If all you are seeing is the mask, click on the Inverted box.

4. Move your timeline marker a few frames, to the point just prior to when the Ghosts make their escape from the box, and then move the entire mask so it covers the Gate.

That’s it. You’re done with this step.

Adding Game Slates

We’re all but done with our Pacman Simulation. All we have to do now is add some graphics to help make it "real."

1. Create a new solid. Layer>New>Solid .. make sure it’s black, and size it so it covers up a portion of the maze you want your Start Game graphics to occupy. (In the illustration below, my black solid layer has been resized, indicated by the red anchor points.) Trim the layer in the Timeline so it is the same lenght as the introduction audio.

2. Make a new Text Layer. Layer>New>Text. Type in your Intro slate text. Mine says "Get Ready."

Access the Character Palette: You will necessarily have to change the fill color …white works well, the stroke properties … mine is set to none, and the font style and size.

Trim the layer so it is the same length as your black solid. Study the illustration below for the layer order, type style, and properties I used.

Repeat Steps 1 and two for your Game Over slate.

Testing Your Pacman Simulation

Tap the 0 Key on the Numeric key pad.

You can also view this video at here:

You’re done. Thank you for working through this challenging tutorial. I hope the process advanced your skill and expertise in After Effects.

Russ Williams


Premium Vector Pack – Stylish Skulls


We have a new set of vector illustrations available exclusively for Vector Premium members. Crafted by the group over at Designious, there are numerous alien and monster skull vector illustrations in this set. You can use them in your next project that needs a scary and stylish skull. Learn more at the jump!

Continue reading “Premium Vector Pack – Stylish Skulls”

Create A Live Performance Rig In Logic Pro – Part 2 – Audio Premium

In this week’s Audio Premium content, Toby Pitman continues his series on how to make a live performance rig in Logic Pro similar to the Sonifi iPhone app.

Like the last tut in the series, this one contains twice the written detail of the average Premium tut, and almost an hour worth of of screencasts is included in the playpack.

To learn more about what you get as part of Audio Premium, read this.

Hello, and welcome to the second part of this Live Rig tutorial. In this part were going to look at how we can convert notes on the keyboard into messages that can activate FX. Well assign controllers like Modulation and Aftertouch to plugin parameters to animate them.

I’ll also show you how you can build reusable blocks by creating Macros and also build user interfaces for those blocks for more intuitive editing. You’ll also learn how to build custom faders and switches.

We’ll also deal with the problems that arise when dealing with Note Off messages in the environment.

If you wanted to know some more advanced Environment techniques then you’ve come to the right place!!!

Table of Contents

  • Turning On An FX Using A Note
  • Switching The FX Off
  • Assigning CC Data To An FX Parameter
  • Working With Different Hardware Controllers
  • Adding Another Effect
  • Recording your Effects Performance
  • Other Applications Of This Technique

What’s included?

  • Project Files
  • 4 Video Walkthroughs

Existing Premium members can log-in and download. Not a Plus member? Join now.


How to Authenticate Users With Facebook Connect


Lately, there’s been quite a fuzz about lazy registration. It turns out that the less the user has to think, the higher the conversion rates are! What a thought! If everybody seems to have a Facebook profile, why not add a one-click user registration? I’ll show you how to do that today.


Step 1. The Setup

MySQL Table

Let’s begin by creating a database table.

CREATE TABLE `users` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `oauth_provider` varchar(10),
    `oauth_uid` text,
    `username` text,
    PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

Quite simple: we will be setting up a table for user information with id, username, first and last name, the URL to the user’s picture, and registered date. Also, we’re adding both an oauth_provider and oauth_uid fields, to distinguish between different third party open authentication protocols and their identifiers. For example, let’s say that, next week, you decide that it’s a good idea to also let Twitter users in. Easy; you just set another value to the oauthprovider, and avoid duplicating oauthuid values.

The Facebook App

Let’s begin by creating a new application. Give it a name and agree to the terms and conditions. Next, grab both the API Key and Secret in the basic tab as shown below.

On the canvas tab, set both the Canvas URL and Post-Authorize Redirect URL to your localhost and path that the script will process — something like http://localhost.com/login_facebook.php?. Note the question mark at the end and the domain; both are required by Facebook. Simply set your hosts file to a valid domain name.

On the connect tab, set the Connect URL to the same value and set localhost.com (or the one you are using) as the Base Domain.

Now save, download the client library, and unzip facebook.php in the srcdir to a new directory created in the root.


Step 2. The Callback

The authentication flow has three steps:

  1. The local script generates a URL asking the user for permission
  2. Facebook returns to the Canvas URL specified with a GET parameter
  3. The GET parameter authenticates the session

Let’s make a quick test before registering and login.

# We require the library
require("facebook.php");

# Creating the facebook object
$facebook = new Facebook(array(
    'appId'  => 'YOUR_APP_ID',
    'secret' => 'YOUR_APP_SECRET',
    'cookie' => true
));

# Let's see if we have an active session
$session = $facebook->getSession();

if(!empty($session)) {
    # Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
    try{
        $uid = $facebook->getUser();
        $user = $facebook->api('/me');
    } catch (Exception $e){}

    if(!empty($user)){
        # User info ok? Let's print it (Here we will be adding the login and registering routines)
        print_r($user);
    } else {
        # For testing purposes, if there was an error, let's kill the script
        die("There was an error.");
    }
} else {
    # There's no active session, let's generate one
    $login_url = $facebook->getLoginUrl();
    header("Location: ".$login_url);
}

Now, go to http://localhost.com/login_facebook.php, and let’s see what happens. If you are redirected to Facebook and requested for permission, we are on the right track.

However, there might be two issues. The first one: if you’re redirected to Facebook, but it shows an error, there might be a missing value in the configuration. Go back to your application settings and check both the Connect and Canvas tabs and make sure the fields are ok as described above.

There might be another issue, where you see an error, like “Uncaught CurlException: 60: SSL certificate problem, verify that the CA cert is OK.” This happens because of the CURL settings. You’ll have to open facebook.php, find the makeRequest() method, and, inside the function, find this line:

$opts = self::$CURL_OPTS;

Immediately following it, add:

$opts[CURLOPT_SSL_VERIFYPEER] = false;

I hate hacking libraries, but I haven’t found another way. Well, let’s continue with user registration. I’ve also added a try/catch statement, because, if there’s an old session keys in the GET params in the URL, the script will die with a horrible error.


Step 3. Registration and Authentication

We’ll next be working with MySQL. Please note that I will not implement a data sanitizer, since I want to keep the code as short and on task as possible. Please keep this in mind: always sanitize your data.

First, let’s connect to the database.

mysql_connect('localhost', 'YOUR_USERNAME', 'YOUR_PASSWORD');
mysql_select_db('YOUR_DATABASE');

Now, let’s work on the $session conditional, in case we have a session.

# We have an active session; let's check if we've already registered the user
$query = mysql_query("SELECT * FROM users WHERE oauth_provider = 'facebook' AND oauth_uid = ". $user['id']);
$result = mysql_fetch_array($query);

# If not, let's add it to the database
if(empty($result)){
    $query = mysql_query("INSERT INTO users (oauth_provider, oauth_uid, username) VALUES ('facebook', {$user['id']}, '{$user['name']}')");
    $query = msyql_query("SELECT * FROM users WHERE id = " . mysql_insert_id());
    $result = mysql_fetch_array($query);
}

Note that I’m querying the database, looking for facebook as a oauth_provider; it’s generally a good idea, if you want to accept other OAuth providers (as twitter, Google Accounts, Open ID, etc.) and a oauth_uid, since it’s the identifier the provider gives to its user accounts.

The oauth_provider field could potentially lead to bad performance if we leave it as a text field type. As such, the best option is setting it to an ENUM type.

We have now a $result var with the values queried from the database. Let’s next add some sessions. Add this line at the beginning of your script.

session_start();

After the empty($result) conditional, append the following:

if(!empty($user)){
    # ...

    if(empty($result)){
        # ...
    }

    # let's set session values
    $_SESSION['id'] = $result['id'];
    $_SESSION['oauth_uid'] = $result['oauth_uid'];
    $_SESSION['oauth_provider'] = $result['oauth_provider'];
    $_SESSION['username'] = $result['username'];
}

As it makes little sense to authenticate a user who is already logged in, just below the session_start() line, add:

if(!empty($_SESSION)){
    header("Location: home.php");
}

And in the scripts which require authentication, just add:

session_start();
if(!empty($_SESSION)){
    header("Location: login_facebook.php");
}

And if you want to display the username, access it as an array.

echo 'Welcome ' . $_SESSION['username'];
# or..
echo 'Welcome ' . !empty($_SESSION) ? $_SESSION['username'] : 'guest';

Step 4. Additional Methods

Facebook has a ton of connect features, but here are four that I’ve found to be the most useful.

Legacy Methods

I might be missing something, but the FQL seems more flexible and easy than the Graph API. Fortunately, Facebook still lets developers use it, altough with the new library, it has changed a bit.

If you want the user id, first name, last name, squared thumbnail for the user picture, the biggest user picture available, and his or her gender, you can use the users.getInfo method.

    $uid = $facebook->getUser();
    $api_call = array(
        'method' => 'users.getinfo',
        'uids' => $uid,
        'fields' => 'uid, first_name, last_name, pic_square, pic_big, sex'
    );
    $users_getinfo = $facebook->api($api_call);

You can check the full list of fields available for Users.getInfo.

It is possible to achieve the same result, using FQL.

    $uid = $facebook->getUser();
    $fql_query  =   array(
        'method' => 'fql.query',
        'query' => 'SELECT uid, first_name, last_name, pic_square, pic_big, sex FROM user WHERE uid = ' . $uid
    );
    $fql_info = $facebook->api($fql_query);

Here’s the list of tables which can be accessed with FQL, as well as the fields available for the table users.

Extended Permissions

Facebook provides applications with some interaction with the user’s data – just as long as it’s authorized. With the old API, the authorization for additional permissions was exclusively available for the Javascript SDK (altough I’m not quite sure). With the new API, we can easily redirect the user to an authorization dialog in Facebook, and return to our site after the access is either granted or denied.

In the following example, we will be redirecting a user to authorize posts status updates, photos, videos and notes, the user’s real email address, birthday and access to photos and videos.

$uid = $facebook->getUser();

# req_perms is a comma separated list of the permissions needed
$url = $facebook->getLoginUrl(array(
    'req_perms' => 'email,user_birthday,status_update,publish_stream,user_photos,user_videos'
));
header("Location: {$url} ");

Here’s a full list of permissions. Note that you can specify both the url to direct to if the user accepts and the url to be redirected to if the user denies. The key for these array elements are next and cancel_url, respectively. Here’s a quick example:

$url = $facebook->getLoginUrl(array(
    'req_perms' => 'email',
    'next' => 'http://localhost.com/thanks.php',
    'cancel_url' => 'http://localhost.com/sorry.php'
));

If not specified, the default is the requesting script’s location.

Checking for Extended Permissions

Since the user can easily revoke permissions, the application should always check if a given permission is granted before using it, specially if it’s about publishing something. We will have to use the legacy API, as it seems it’s not fully implemented with the new one yet.

    $uid = $facebook->getUser();

    # users.hasAppPermission
    $api_call = array(
        'method' => 'users.hasAppPermission',
        'uid' => $uid,
        'ext_perm' => 'publish_stream'
    );
    $users_hasapppermission = $facebook->api($api_call);
    print_r($users_hasapppermission);

The ext_perm will only support the old list of available permissions.

Publishing to the Wall

Let’s post something to the wall after verifying the user has the publish_stream permission.

    # let's check if the user has granted access to posting in the wall
    $api_call = array(
        'method' => 'users.hasAppPermission',
        'uid' => $uid,
        'ext_perm' => 'publish_stream'
    );
    $can_post = $facebook->api($api_call);
    if($can_post){
        # post it!
        $facebook->api('/'.$uid.'/feed', 'post', array('message' => 'Saying hello from my Facebook app!'));
        echo 'Posted!';
    } else {
        die('Permissions required!');
    }

Essentially, we are making an API call to /<user_id>/feed, using the POST method (second argument) and an array as a third argument for the data to be sent. In this case, this third argument supports message, link, picture, caption, name and description. Here’s the code:

$facebook->api('/'.$uid.'/feed', 'post', array(
    'message' => 'The message',
    'name' => 'The name',
    'description' => 'The description',
    'caption' => 'The caption',
    'picture' => 'http://i.imgur.com/yx3q2.png',
    'link' => 'http://net.tutsplus.com/'
));

Here’s how it is posted.

Some Additional Information you Should Know:

The user can easily revoke permissions with two clicks in his or her wall. You should heavily test what might happen if a user revoked one or more permissions that are vital for the proper functioning of your website, or even if the application is fully removed. This is important.


5. Conclusion

While Facebook’s authentication capabilities are indeed useful, since so many people are on Facebook these days, using it as the only method of authentication in a site is not recommended. What about those who don’t have Facebook accounts? Are they not allowed to access your application? Thanks for reading!

What Are Your Must-Read Blogs?

Most of our information these days seems to come directly from the web.  There are “traditional” news sites such as The Guardian and CNN as well as print media that have integrated (or even fully migrated) their print edition with their online presence such as the New York Times or Wired Magazine.

And then there’s blogs.

Blogs can really narrow down things for readers.  They can focus on one specific topic (or one specific mission) and have large readership on a daily basis because of it.  Niche blogs are popping up all over the web, and there seems to be no sign of this stopping anytime soon.  Bloggers are now being touted as journalists as well – something that would have been unheard of perhaps even as recently as a year ago.

Which blogs are on your “must-read” list? What’s on your RSS reader? Do you read a variety of blogs or do you focus on one or two areas of interest?  Let us know in the comments.

The Complete Beginner’s Guide to Natural Light

If you want to improve the quality of your photography, one thing you can do right away is learn to use natural light better. The good news is that unlike good quality lenses and camera bodies, natural light is free. The best photographers seek out the best quality light for their subject. Their quest for better photos is paralleled by a search for better light.


“Painting With Light”

The word photography is derived from the Greek for ‘painting with light’. This is a good description – a photograph is made from the light that enters your camera’s lens and hits the sensor (or film). Without light you would have nothing.

Broadly speaking, there are two types of light – natural and artificial. Natural light (the topic of this article) comes from the sun. The quality and quantity of the light depend on where you are, the weather conditions and time of day.

As photographers, we need to be students of light – observing the lighting conditions and learning why light behaves like it does. Then we can understand how light affects our photos and how to make the best use of it.

The more you understand light and how it affects your photos, the better a photographer you will be. To help you out, we’ve put together a brief guide to the main types of natural light and how to make the most of them.


Hard Light

The light from the sun on a sunny day is hard light. It’s strong and direct and casts deep shadows with hard edges. In the middle of the day, especially in the summer, hard light can be very ugly. Avoid taking photos at this time if you can.

Hard light is best at either end of the day, shortly after the sun has risen and just before it sets. Photographers call this period the golden hour, because of the quality of the light. If the sky is clear, the light is still hard, but it’s a great deal softer than in the middle of the day. It also comes at your subject from a low angle which reveals form and texture and is much more interesting than midday light.

This photo of a Mexican pinata was taken in harsh, tropical sunlight. The hard light brings out the colours of the pinata against the deep blue sky.

Hard light is also good for architecture and bringing out colours. This photo was taken in La Boca in Buenos Aires. The sunlight brings out the strong colours (I used a polarising filter for both photos to deepen the colours and turn the sky deep blue).


Soft Light

Soft light describes the type of light that you find in the shade or on a cloudy day. Any shadows have soft edges. Soft light, especially on a cloudy winter’s day, can seem grey and dull, without much potential for photography.

The key to using soft light is to understand that it has very little contrast. It’s the opposite of hard light from the sun.

Soft light is great for taking photos of people, especially portraits. If you’re outside on a sunny day, taking photos of people, find some shade and take photos of them there. The results will be much better.

Soft light is also suitable for taking photos in rainforest and woodland, and for still life and flowers. On a cloudy day, avoid including the sky in your photos – it usually just comes out white.

This photo was taken on a cloudy day. Soft light is ideal for photographing details like this hand made stirrup. This photo was taken in the middle of the day – if the sun had been out the photo would look completely different.

This photo of a gaucho was taken on the same day. The soft light is perfect for portraiture; hard sunlight would have ruined the mood of this photo. It’s no coincidence that both these photos are in black and white – soft light is also wonderful for monochrome work because the light brings out the subtle tones and textures in the photo.


Backlight

This is my favourite type of light. Backlight is created when the light source is behind the subject. Backlight, like hard light, has lots of contrast. Also like hard light, it’s normally best for photos at the end or the start of the day. Backlighting from the sun at any other time of the day has too much contrast.

Backlighting is good for landscapes, portraits and architecture. It’s a powerful, moody, evocative type of lighting. It is very dramatic if combined with weather conditions like mist or fog.

You’ll need to keep your lens scrupulously clean for shooting backlit subjects, as the light will shine right on the front element of your lens, causing flare. Sometimes flare is unavoidable – if this happens to you the best way to deal with it is to work the flare into your composition. Make it look like a deliberate part of the photo, rather than an unwanted side effect.

This cathedral is backlit. The statue and towers are semi-silhouetted by the strong light. The photo was taken in the evening. The light is hard, but much softer than at midday.


Dramatic Light

Dramatic light is created by dramatic weather such as a thunderstorm. It’s the type of light that you see when the clouds clear after a rain storm, or if the sun breaks through the clouds on a rainy day near sunset.

Dramatic light is ideal for photographing landscapes, seascapes and architecture – almost anything outside. If you are confronted with a scene lit by dramatic light, treat it as a gift and take as many photos as you can while it lasts. Dramatic light normally doesn’t last very long, and it may not return.

This photo was taken during a violent thunderstorm – the lightning was real and not added in Photoshop. The mountains have been turned into dramatic silhouettes by the light.

Stay aware of the weather when taking photos like this – a few minutes after taking this photo I realised that a band of torrential rain was approaching and we left the lookout very fast, just in time to avoid getting completely soaked (it’s also a good idea to avoid high ground in the middle of a thunderstorm!).


Sunrise and Sunset

At sunrise and sunset the light is beautiful and full of colour. It has the potential to be any of the types of light we’ve discussed so far – soft, hard or dramatic. If the sun is out your subject will be backlit. The light can change between all of these states very quickly.

No matter what your subject, sunrise and sunset are wonderful times for taking photos. This is especially true for landscapes and seascapes, but also for architecture and nature. This is your time for creating evocative photos full of mood and atmosphere.

It’s the kind of light that travel photographers love because it makes everywhere look so beautiful. Professional landscape photographers love this time of day so much that they get up early to make the most of sunrise and stay out late for the sunset.

Sunset over the RÌo de la Plata, Uruguay. The colours are beautiful. Photos like this are bit of a cliche, but still fun to take.


Interiors With Natural Light

You can use the natural light coming through doors and windows to photograph interiors. You have to pay lots of attention to where the light is coming from when you’re doing this. The light, even on a cloudy day, will be hard because it’s coming in through the doors and windows. If you include open doors or windows in your photo, they will burn out because they are so bright compared to the interior.

The good thing about this type of light is that it can be very dramatic and moody, especially inside an old building. Some people will solve the problem of shooting in these conditions by using HDR techniques. But for me, HDR photos often have an unreal appearance that I don’t like. I don’t want to see every detail; I like dark shadowy corners and prefer that something is left to the imagination.

An old shop in Argentina. The light coming in through the doorway is very moody and evocative. It suits the old style of the shop, which is like a living museum, perfectly.


Using the Light

Next time you’re out taking photos, think about the natural light. Does it suit your subject? Would the light be better at a different time of day, or in different weather conditions? It may be that to get the best out of a location, you have to return at another time when the light is better.

If you remember just one thing from this article, it should be this: that natural light is at its best at the beginning or end of the day. These are the best times to be out taking photos. If you haven’t tried it before, do it soon. Nothing will improve your photography so fast.