Gideros Mobile Tutorial 6: Fun with Events

This is a continuation of a previous tutorial. We will add some more effects in this one and we will also learn how to use some existing libraries. The entire lesson with all needed files can be downloaded here. You can use your existing main.lua file from previous tutorial or you can start new one.

Ok, so we have a rotating ball that listens to ENTER_FRAME (rotates the ball every frame) and MOUSE_DOWN (changes rotation) events. Now lets add two more events to make this “game” more interactive. We will add MOUSE_UP and MOUSE_MOVE. MOUSE_MOVE will be used when we move the ball (by holding down the finger on screen) and MOUSE_UP will be used (triggered) when we let the ball go (lift the finger off the screen). We will also use another (Lua) library called GTWeen and the easing effects.

Instead of just dumping entire code I will be pasting part by part. These parts form main.lua file.

Part one: Everything is the same like before except that we load another soundfile that will be used as a ball bouncing when we release it.

-- you can apply some settings to your entire application
application:setKeepAwake(true)
application:setScaleMode("letterbox") --proper "full screen" scaling for most devices

-- global direction variable,rotate counterclockwise -3
direction = 3

-- load the textures and create bitmap objects
--2nd texture parameter can be set to true to get anti-aliasing
local field = Bitmap.new(Texture.new("gfx/field.png",true))
local ball = Bitmap.new(Texture.new("gfx/ball5.png",true))

-- load sound that will be played when we press on ball
local soundJump = Sound.new("snd/jump.mp3")
local soundBounce = Sound.new("snd/bounce.mp3")

-- set the anchor point in the center of ball so we can rotate it
ball:setPosition(120,150)
ball:setAnchorPoint(0.5,0.5)

part 2: First, we added a GTween tween to changeBallDirection function.If you used Flash then you know what tweens are but basically it is an animation that is generated between 2 frames we specify.The term tween comes from the words “in between”. Example: We give GTween starting and ending frame of a object and GTween will create a transition. It can be moved from/to, it can be scaled from/to etc.

GTween.new(ball, 0.3, {scaleX = 2, scaleY = 2}, {ease = easing.linear})

What this does is it takes the ball object and scales both x and y times 2 in 0.3 seconds and using the easing.linear effect. Second, we create a new function that will move the ball as we slide the finger on the screen while still holding it. I’m not going to explain the mathematics of this except that we get ball coordinates with getX() & getY() and we set them with setX() & setY().

Here is the full code of part 2:

-- function rotating ball - executed every frame
function rotateBall(event)
	ball:setRotation(ball:getRotation()+direction)
end

-- function scale ball - executed every mouse press
-- it is not actually mouse,it means no multi touch
function changeBallDirection(event)
	if ball:hitTestPoint(event.x, event.y) then
		GTween.new(ball, 0.3, {scaleX = 2, scaleY = 2}, {ease = easing.linear})
		soundJump:play()
		direction = math.random(-20,20) --random rotation speed(left or right)
	end
end
--move the ball
function moveBall(event)

	if ball:hitTestPoint(event.x, event.y) then
		local dx = event.x - ball:getX()
		local dy = event.y - ball:getY()

		ball:setX(ball:getX() + dx)
		ball:setY(ball:getY() + dy)
		ball.x0 = event.x
		ball.y0 = event.y

		event:stopPropagation()
	end
end

Part 3: here will just attach event listeners that will call specific functions.

-- rotateBall function will be called on every frame change
ball:addEventListener(Event.ENTER_FRAME, rotateBall)
-- when we click on the ball it will change rotation and "jump" up
ball:addEventListener(Event.MOUSE_DOWN, changeBallDirection)
-- when we move the mouse then ball also moves
ball:addEventListener(Event.MOUSE_MOVE, moveBall)

Part 4: As you see the way we always create event is that we first write a function that does what we want and then pass it as a second argument to addEventListener function. You can also do it with anonymous function, especially if what the function does is in one or two lines so you don’t end up creating tons of strange named functions. Below we add Event.MOUSE_UP to ball:addEventListener but instead of passing function name as second parameter we create anonymous function and put the entire code there. In our case we use another GTween effect that returns the ball to starting scale 1 in 1.5 seconds but this time it uses outBounce easing effects so it looks like the ball is bouncing.

ball:addEventListener(Event.MOUSE_UP, function(event)
if ball:hitTestPoint(event.x, event.y) then
	soundBounce:play(30)
	GTween.new(ball, 1.5, {scaleX = 1, scaleY = 1}, {ease = easing.outBounce})
	end
end
)
stage:addChild(field)
stage:addChild(ball)

Try this and if you did everything correctly you should see a spinning ball. Now press AND hold the ball with your finger and the ball will scale to 2 times size in 0.3s .Drag it around and the ball will follow you. Now release it and it will fall down in 1.5s using outBounce effects ๐Ÿ™‚ Isn’t that great? We can almost call it a game (if the goal of the game is to die of boredom moving the ball around ;).

Play with it a little, change GTween easing effects, maybe change graphics,sound effects..

Note: You can read more about GTween and it’s easing effects here. There are few “glitches” in the code – I used some random sound for bounce so it is not synchronized and also if you tap the ball too fast then the effect will fail because it will try to start new tween before it finished old one. Just ignore it for now.

SyntaxHighlighter Evolved Lua Brush (Language) for WordPress

If you need to add Lua support for WordPress SyntaxHighlighter Evolved plugin then here is one way:

Download this ZIP file. It contains 2 files:

  • shBrushLua.js – Lua Brush file
  • shBrushLua.php – WordPress plugin

Extract these 2 files and use FTP to navigate to your plugins folder (usually /public_html/wp-content/plugins), create new directory, for example syntaxhighlighter-brushes, and upload these 2 extracted files.

Go to WordPress admin -> Plugins -> Installed Plugin and activate “SyntaxHighlighter Evolved: Lua File Brush”,

Now you will be able to use Lua language with this code:

[lua]
— some Lua code here
print “Hello World!”
[/lua]

and it should display something like this :

-- some Lua code here
print "Hello World!"

Create a WiFi hotspot in Windows 7 and share Internet connection

If you don’t have WiFi router you can still share your internet connection via your PC. I was using connectify.me software and it did the job but it felt bulky,it disconnected at random times (free version) and my laptop fan was on full speed all the time,which was slowing down my PC. I was very surprised when I learned how easy it is to do it by yourself (on windows 7 at least). All you need to do is enter few commands and enable ICS and that’s it! What is great is that you can use this connection with your Nexus 7 or any other smartphone.

1. Click Start and type cmd, then right click cmd.exe and select “run as Administrator”:
cmd run as administrator

2. Run this command (I used “My net” as SSID and “elcoderino” as pass so replace it with your values)

netsh wlan set hostednetwork mode=allow "ssid=My net" "key=elcoderino" keyUsage=persistent

This will create “Microsoft Virtual WiFi Miniport adapter” and will also set up your hostednetwork. Now you need to enable Internet Connection Sharing (ICS) or Network Bridging for this new adapter (don’t worry, it is just few clicks. I enabled ICS connection but you can also bridge networks)

3. Now you simply start or stop new hosted network with these commands (please keep in mind that cmd.exe needs to be “run as administrator” – check step 1)

// to start hostednetwork type
netsh wlan start hostednetwork
// to stop hostednetwork type
netsh wlan stop hostednetwork 

and that’s it! You should now have a working WiFi hotspot! Try connecting with your smartphone or tablet. Why install or even pay for the software when you can have it with few simple steps?

Share localhost over the internet with ngrok

One of the more annoying things when developing on your local computer is that your clients or friends can’t see what you develop. You can upload it on your web server or you can work directly on the web server but that is inconvenient and slow. So I was very happy to discover this great tool called ngrok. There are similar tools (localtunnel etc) but this one is really easy to use.

Who is your daddy and..no..wait..what is ngrok and what does it do?

Ngrok is a cool little program that creates a tunnel from the public internet (http://subdomain.ngrok.com) to a port on your local machine. You can give this URL to anyone to allow them to try out a web site you’re developing without doing any deployment. Of course your local server has to run at the time of sharing but that is not a problem – you just leave your PC on.

How do I run this ngrok?

With ngrok it is super simple to expose a local web server to the internet. On Windows you just download ngrok.exe, unzip it some folder and then in command prompt (cmd) you just tell ngrok which port your web server is running on.

This is the most simple way (This opens port 8080 on your local machine to the internet). Type this in your command prompt:

ngrok 8080

You will see something like this :

Tunnel Status                 online
Version                       0.11/0.8
Protocol                      http
Forwarding                    http://345355bc.ngrok.com -> 127.0.0.1:8080
Web Interface                 http://localhost:4040
# Conn                        0
Avg Conn Time                 0.00ms

Of course the port (in this case 8080) has to be the port that your localhost is running on. Now just give the generated URL (in our example http://345355bc.ngrok.com) to your client or friend and let them test out your application.

You can do a lot more with ngrok, like inspecting your traffic, XML/JSON syntax checking, replaying requests, requiring passwords to access your tunnels, accessing your tunnels over HTTPS, forwarding non-HTTP services, forwarding to non-local services and more.

Check out ngrok here.

Simple relationship example in Laravel 4

Today I tried to create a simple relationship with Laravel 4 Eloquent but because I am still learning Laravel I spent more than an hour to figure it out. I searched the net ,forums etc but I simply didn’t find what I was looking for or it was for more complicated example. Relationships can be quite complicated ( like we all don’t know this ๐Ÿ˜‰ ) so I am not going to go into details about what they are in this post – I am going to show you a specific solution for a specific problem.

Display the name of the country of specific person with Eloquent relationships

OK, so we have a table Customers and table Countries. Table Customers has fields like first_name,last_name, telephone etc but also field/foreign key country (int). Table Countries has the list of all countries in the world. The name of the specific country in table Countries is stored in the field short_name. We have admin and in the admin we have a page that lists all customers.

Defining the relationship between two tables

Customer can only have one country but country “has” many customers.(for example several customers can be from US). So in our case we have one-to-many relationship.

In the controller (that deals with customers) we have this code:

	public function getIndex()
	{
		// Grab all the customers
		$customers = Customer::orderBy('created_at', 'DESC')->paginate(10);
		// Show the page
		return View::make('admin/customers/index', compact('customers'));
	}

and in our admin/customers/index.blade.php view we loop through results set like this(excerpt):

      @foreach ($customers as $customer)
        <tr>
            <td>{{ $customer->first_name." ".$customer->last_name }}</td>
            <td>{{ $customer->country }}</td>
            <td>{{ $customer->telephone }}</td>
        </tr>
        @endforeach

Simple but it gives us this:

Relationships before, Laravel

Now we could create a function that would return a name of the country like this Customer::countryName($customer->country) but why do this when it can be done much more elegantly.

Laravel Eloquent relationships to the rescue

Open the Customer.php model and add this method/relationship:

    //relationship with country table 
   public function country() {
        return $this->belongsTo('Country');
    }

Now let’s go back to our admin/customers/index.blade.php view and check this line:

<td>{{ $customer->country }}</td>

We can now access the country name with this code : $customer->country()->first()->short_name

but it gets even better: Due to Eloquent’s Dynamic Properties we can shorten our call so replace the above line with:

 <td>{{ $customer->country->short_name }}</td>

Save, refresh your page and voila, we see this :

Relationship final laravel

As you can see, relationships in Laravel 4 can be very useful and elegant way to solve such problems. In this post I didn’t explain every funtion call because I didn’t want it to get too confusing. I will write more about relationships in some of the future posts.

Added: You can read more about database relationships here: Database table relationships: One-to-One vs. One-to-Many vs. Many-to-Many

Enable Gmail Tabs – Tabbed Inbox

Gmail’s inbox Tabs are a very cool new Gmail feature that brings order to your inbox.

gmail inbox tabs

To enable it, click the gears button and try to find “Configure inbox”.

tabs inbox gmail

Click on “Configure inbox”, select the tabs that you wish to enable,click Save and you can now use the new feature.ย  In case you do not see “Configure inbox”, check back later.

How to embed styled tweets in your posts or pages

A lot of people don’t know that there is an easy way to embed tweets on your site with all the formatting and styling so they look just like on twitter.com. In addition, tweet will also contain avatar, reply,favorite,follow and other buttons so it is also functional.

For example look at this embedded tweet:

Looks nice, doesn’t it? Good news is that it is very simple but you need to go to twitter.com and follow these steps:

1. When you see a tweet in your stream that you would like to embed simply click on the date (when the tweet was posted) link – in our example above that link/date is “22 Mar 06”.

2. When the tweet is displayed click on the “Embed this Tweet” link and pop-up box will appear.

3. Copy the entire HTML code and paste it into the source (HTML) code of your page anywhere you want (inside body tag).

This is how the code for above tweet looks like:

<blockquote class="twitter-tweet">
<p>just setting up my twttr</p>&mdash; Jack Dorsey (@jack) 
<a href="https://twitter.com/jack/status/20" data-datetime="2006-03-21T20:50:14+00:00">March 21, 2006</a>
</blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>

Keep an eye on this line :

<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>

This JavaScript,which is fetched from twitter website, makes your tweet embed look all nice like in our example above. If you forget to copy it your embedded tweets will not be styled properly.

If you embed only one tweet per page then you can include this line after blockquote. If you embed several tweets then include this line only once, somewhere at the bottom of the page or inside meta tag.

Stylesheets / CSS not or partially loading, site partially loaded

Every now and then I encounter a problem where several sites that I visit fail to displays CSS. It looks something like thisย  (Gizmodo website):

css not loading, website partialy loaded gizmodo

The problem appears when something goes wrong while you are deleting browser cache,cookies etc. In my case it usually happens when I use CCleaner (free tool for cleaning your Windows PC) and I accidentally open Firefox (or other browser) while CCleaner is deleting the cache.ย  Websites start to look like above screenshot and refreshing the page doesn’t help.

The solution is to refresh the page with CTRL + F5, which forces browser to redownload the entire site from internet and not from local cache. This solves problem only for that site so what I do is close all browsers and run CCleaner again.

Sublime Text 2 opens “instant file search” instead of printing left square bracket in Windows

This problem only appears on certain keyboards and languages where left and right square brackets are placed on letters F and G. Even if you have similar problem with different keyboard or key binding /letters you can still use this solution.

I was using Sublime Text 2, which is really fantastic editor, on Windows 7 and encountered a weird problem. When I pressed AltGr+F Sublime Editor 2 didnt print “[” (left square bracket) – it opened Instant File Search tool instead.

The reason for this is that Windows sees AltGr as Ctrl+Alt, and therefore AltGr+F will be understood as Ctrl+Alt+F, which is a default keymap for Instant File Search tool.

To fix this you need to override the default Ctrl+Alt+F shortcut so it will insert the desired character by inputting that shortcut in user key-bindings.

Do this:
1. Select “Preferences > Key Bindings – User” in Sublime Text 2 menu
2. Paste the following code there:

[
{ "keys": ["ctrl+alt+f"], "command": "insert", "args": {"characters": "["} }
]

If your Key Bindings – User file is not empty then just add the code without the square brackets (line 1 and 3) and dont forget to add comma at the end or at the begging of the line.

Stop WordPress Asking For FTP details When You Install / Upgrade Plugins

When you want to install or upgrade a plugin, WordPress will most probably display this message:

Connection Information

To perform the requested action, WordPress needs to access your web server. Please enter your FTP credentials to proceed. If you do not remember your credentials, you should contact your web host.

If you are on shared hosting you might not have this problem but if you are on a VPS or Dedicated server you will most probably get asked to supply FTP credentials every time you want to install or upgrade plugin or even WordPress. This can become an annoyance if you install plugins a lot so this is one of the first things I always fix when I install new WordPress site.

Here is how to solve it: open your wp-config.php file (by default it can be found in your root WordPress directory) with text editor and simply add your ftp login information near the bottom of the wp-config.php file (just above the /** Sets up WordPress vars and included files. */ comment for example):

//*add your FTP credentials*
define('FTP_HOST', 'host_IP_or_FTP_url');
define('FTP_USER', 'FTP_username');
define('FTP_PASS', 'FTP_password');
//*If you like and can use a SSL connection set this to true*
define('FTP_SSL', true);

After you do this your won’t be asked for FTP credentials anymore. There are other solutions like settings permission with chown via shell or installing suPHP on your server but this one seems to be the easiest.

If the above fails for whatever reason you can comment the above code and try adding the following code in the wp-config.php file,somewhere at the top:

define( 'FS_METHOD', 'direct' );
define( 'FS_CHMOD_DIR', 0777 );
define( 'FS_CHMOD_FILE', 0777 );

This forces files to be writable by the server. You should only use this if adding FTP credentials method fails.