Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Friday, April 13, 2012

Exporting MySQL to Excel XML with formatting through PHP


The Requirement
Over the last couple of days I have been working on creating a way of getting data from a MySQL Database and getting this into an Excel spreadsheet for a project for a client.  This is something I had done before so I thought it would be no big task.  In fact, phpMyAdmin (apparently, though I haven't tried it) has a way of exporting data into a CSV file which is readable by excel.

The Problem
The problem is, a CSV file is a simple dump of data into a file, which contains no formatting, and so can make the spreadsheet look pretty ugly as well as hard to read.  This is obviously not what a client, or anyone wanting to analyse the data from a spreadsheet wants.

The Solution
So after hours and hours and hours of searching the internet and trying all different methods (none of which seemed to work correctly - for me) for one reason or another, I decided to reverse engineer an Excel file; create a basic spreadsheet, format it as required, and save it as an Excel XML file.  Then all I would have to do is open it up in a text editor, see how Excel was formatting the file, and recreate this with some php code and adding in the functionality to get the data from the required database then save that into an xml file.

If you want to do a lot of formatting to your spreadsheet,  then I recommend you reverse engineer your own Excel file sheet, and recreate it with php yourself.  If there is a quicker way of doing this, let me know, but this is the only way I could personally get it working.

Tools
Something I found very useful for this was a basic online tool called XML Pretty Print (http://xmlprettyprint.com/) that converts ugly xml with all the tags pushed up together in a very hard to read way into a much more organised, easy to look at layout.  This made it a lot easier to separate the different lines of XML code when it came to creating the php file.

I also used Compare My Files (http://www.comparemyfiles.com/) to compare the XML file I exported from Excel with the XML file created from the code when it wasn't working, to see what was wrong with the php created XML file.


Example
Here is what I ended up with.  It took quite a bit of playing around with to get it working fully.  The slightest mistake and Excel would show a blank spreadsheet.  (To be honest, I was using Open Office, so Excel may have opened it, I don't currently have Excel installed to test it on).

Feel free to play around with this and see how it works for you.


//Connection to Database - Fill in with the details for your database
$host = '';
$user = '';
$pass = '';
$database = '';
$table = '';

//Code to connect to the database
$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host."); 
mysql_select_db($database, $linkID) or die("Could not find database."); 

//Query the database - select all fields 
$query = "SELECT * FROM `$table`"; 
$resultID = mysql_query($query, $linkID) or die("Data not found."); 

//The XML code. $xml will store the entire xml structure and will be
//saved to an xml file at the end.

$xml = '';
$xml .= '';
$xml .= '';

$xml .= '';
$xml .= '';
  $xml .= '';
   $xml .= '3'; 
   $xml .= '#c0c0c0'; 
   $xml .= '';
   $xml .= ''; 
   $xml .= '4'; 
$xml .= '#ff0000'; 
   $xml .= '';
   $xml .= '';
$xml .= '';

$xml .= '';
$xml .= '9000'; 
  $xml .= '13860'; 
   $xml .= '240'; 
   $xml .= '75'; 
   $xml .= 'False'; 
   $xml .= 'False';
$xml .= '';


//STYLES - This is the style information used for the rows, 
//columns and individual cells

$xml .= '';
$xml .= '';
  $xml .= '';
  $xml .= '';
  $xml .= '';
$xml .= '';
$xml .= '';
$xml .= '';
$xml .= '';
//END STYLES

//WORKSHEET
$xml .= '';
//TABLE
$xml .= '
';
   $xml .= ''; 
  $xml .= '';
$xml .= '';
$xml .= '';
$xml .= '';
//HEADER ROW
$xml .= '';
//CELLS
$xml .= '';
  $xml .= 'Order ID'; 
   $xml .= '';
$xml .= '';
   $xml .= 'Invoice Number'; 
  $xml .= '';
 
$xml .= '';
   $xml .= 'Customer ID'; 
   $xml .= '';
 
$xml .= '';
   $xml .= 'Store Number'; 
   $xml .= '';
  $xml .= '';
   $xml .= 'Total'; 
  $xml .= '';
//End CELLS
   $xml .= '';
//End HEADER ROWS
//Code to get rows from database - you will have to replace the row names with the rows in your database.

for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++)  //Loop through all rows and do the following for each
$row = mysql_fetch_assoc($resultID); 
//ROWS
$xml .= '';
//CELLS
$xml .= '';
$xml .= ''. $row['order_id'] .''; 
$xml .= '';
$xml .= '';
$xml .= ''. $row['invoice_no'] .''; 
$xml .= '';
$xml .= '';
$xml .= '' . $row['customer_id'] .'';
$xml .= '';
 
$xml .= '';
$xml .= ''. $row['store_name'] .''; 
$xml .= '';
$xml .= '';
$xml .= ''. $row['total'] .''; 
$xml .= '';  
//End CELLS
$xml .= '';
//End ROWS
}
  $xml .= '
';
//End TABLE
   $xml .= ''; 
  $xml .= '';
  //End WORKSHEET

$xml .= '';
//End WORKBOOK

//Write the entire xml structure and data to an xml file "xmlOutput.xml"
$fp = fopen("xmlOutput.xml", "w");
fwrite($fp, $xml);
fclose($fp);

echo "XML Data written to xmlOutput.xml";

?>




Monday, September 22, 2008

C# Event Handling

In an attempt to broaden my programming skills, and more specifically my C# skills, I have been learning how to create event listeners with Visual C#.  I am learning how to recreate the interface in my flash version of wizED (which I still havn't uploaded yet, I am going to work on a webpage to put it, and the finished game on soon).

Here are some sites I have been looking on for the information:
http://articles.techrepublic.com.com/5100-10878_11-1050284.html This is nice and basic, starting from how events are added when you add a control to the form, etc.
http://articles.techrepublic.com.com/5100-10878_11-1053743.html?tag=rbxccnbtr1 This article follows on and goes into more depth about custom added events, dynamic events etc

http://secure.codeproject.com/KB/cs/event_fundamentals.aspx - goes into more depth about delegates and dynami event handling.  A lot to read, but useful.

Update: although I understood the concept, I was still struggling getting a click event to work until I came across this page which made it really reallly simple: http://www.csharp-station.com/Articles/EventHandlingInCSharp.aspx

Friday, September 19, 2008

Programming Lessons

Today I have been looking into using event handlers/listeners in C#

Websites I have looked at:

I am hoping to create a C# version of the level editor for my flash game 'Wizards' so trying to improve my C skills a bit.  Also been looking up classes and some other stuff, no examples of any working code yet though.

Website update

Over the summer I started learning some php and use of mySQL databases in websites.  After finishing the current version of the Wizards game (which is not really finished, but I'm having a break) I came back to doing a little bit of web stuff.  Here is the page at the moment of writing this page http://www.colinjensen.co.uk/~gibboco/1/index.php  (its on my friends website, not got around to getting my own domain name yet).  Theres nothing much there, and I know the design is pretty much none existant.  The only thing the site does is gets the information from the database and displays different posts in the blog depending on which category is selected. Nothing amazing and needs work but it's a start.

Monday, September 15, 2008

WizED 1.1 (for Wizards)

Instructions for the editor for my flash game Wizards (WizED v1.1) 

I am putting this in my blog as I don't have a website for the game set up yet, though I should do shortly.  As the editor (along with the game) have been quite rushed, and since it has all been a learning experience, programming things I have not attempted before, things will not all run perfectly.  I have made no attempt at error handling as of yet.  If a problem arises, the game will most likely crash.   

I know this game isn’t perfect, but I have worked hard on it and have learnt quite a lot (mainly that I need to learn better ways of doing things) and I hope you enjoy trying it and messing around with the editor.  I know there are problems with it, and I know it can be frustrating, but I would really appreciate any useful criticism and ideas on how to improve the game and the editor.  I will be working on updates now and again so hopefully the game will begin to improve over time. 


The Editor
With some objects, such as the collectable stars, and mover objects, once they are placed, there is no way of removing them without starting the level design from scratch (restarting the editor).  Mover objects can be drawn over with the blank tile, but this will not actually remove it from the level.

Also, I have found it very hard finding any information on saving information from a flash file to the local computer.  For this reason, to save your level you must copy the level information into a text file and save it in the 'Levels' folder of the 'Wizards 2_2' directory (which you will have to have copied or downloaded onto your computer from the CD-Rom or website).  The next version will allow levels to be loaded from webpage url's.

Unfortunately, for now anyway, once you have clicked the 'make' button, you will not be able to go back and edit your level using the level editor.  Also, there is no way as of yet for importing levels to edit using the editor.  This is something I will be adding in the next version.  So before you click 'make', ensure that the level is exactly how you want it.


Block Brushes

The normal tile brushes are very easy to use and work well.  Simply choose the tile (there are three different tiles available in this version of the editor, and four unused ones (red/other colours).  There is also the blank tile (which has a red line through it) which is used for removing tiles you have placed.  Once you have selected your tile, click and drag around on the map to place the tiles down.  You can place as many tiles as you like without slowing down the game any considerable amount.  If you go wrong, use the blank tile.  You can use the red tiles if you wish, they will just show up as they do on the editor when playing the game (in the current version at least).


Collectable (small) Stars 
The small stars are the collectable items in the game.  You must have at least one of these on your map somewhere or the 'make' button wont function.  Ensure that you put the stars in places that are reachable by one of the characters (in Wizards v2.2, characters can jump approximately 4 blocks high.  This may vary in later versions of the game).
  The star brush icon is small so look at the output box at the bottom left of the screen to ensure it reads ‘Star Brush’ before clicking on the map.  You can only place one star at a time, and only one in each box.  In v2.2, stars are always placed in the bottom left of the box (again, may vary in later versions).  Be careful placing stars as they cannot be removed in the editor.  Although stars do not have to be reachable for the ‘make’ button to function, the level exit stars will not appear until all of the smaller stars have been collected in the level, meaning the level will not be completable.   

Also be careful with the amount of stars that you place, as they can start to slow the game down considerably.


Exit Stars
A level can only have, and must have two exit stars to be able to use the make button, and for the game to load it.  Ensure the stars are reachable by the characters (at the same time) to make the level completable.  Although you cannot directly remove exit stars, if you have the exit star brush selected and click on the map when two exit stars already exist, then both exit stars will disappear. 


Mover Blocks
Mover blocks are the big pain with the game and the editor.  These need a lot of work until they are fully usable within the game.  To create a moving block, click the red block to the right of the large star at the top of the screen.  The output text will read ‘Mover Block.  Select a tile type’.  Although you must select a tile type, this is completely irrelevant as all blocks appear as block type 3 (the four brown blocks).  Once a tile type has been selected, type in a number in both the text boxes beside the mover brush.  The top number refers to how many blocks above the selected one the mover block will move up to, and the bottom number how for the mover block will move down to.  There is no cap on the number you can enter, though errors will probably get thrown back at you if you type huge numbers (I’ve not tried). 

When moving blocks move at different heights to each other, the character gets confused when landing on one and starts jumping up and down on the lower ones.  This is annoying and unplayable, so I advise having all moving blocks at the same height.

There is nothing stopping a mover block moving down from the top screen to the bottom screen or vice versa.  I don’t think that I have actually implemented the ability for the bottom character to use mover blocks, but this will definitely be added in the next version.  As stated before, mover blocks cannot be deleted using the editor. 


Editing with Text Editor
If you really want to edit the level after you have created it and found something isn’t working right, then it IS possible to open the xml file in a text editor and make changes.  If you are deleting a star or mover item, ensure that you edit the ‘starNum’ and ‘moverNum’ tags near the start of the file relevant to the changes made.


Saving your Level

When you press the make button, assuming no errors come up, the xml data for the level will appear in a text box.  The text is automatically copied to the clipboard so just open up your text editor and paste it in (the file may look a bit odd but don’t worry).  Save it in the Levels folder as an xml file (e.g. myLevel.xml).  Now when you run Wizards2_2.exe (from the same file as the Levels folder sits) just type in ‘Levels\myLevel.xml’ or whatever you have saved it as in the text box and click ‘Load’ to start your level.

Saturday, September 06, 2008

[XML] Loading level layouts into tile based Flash Game

Introduction


I am starting the XML stuff for my wizards game from scratch. Yesterday after trying several methods of getting multiple levels to load, I found out about using XML to load in data to a flash file.  I used several websites to help me understand the concept (Emanuel Feronato,8 Bit Rocket and by far the most useful and easy to understand, Kirupa).

 

Anyway, thinking I had learnt completely how to use it, I dived straight in to adding the code into my project.  This sort of worked.  I am still unsure why it DIDN'T work completely.  I managed to load in the level and display it on the screen, but I couldn't work out why it wasn't showing properly (the tiles were all the same, as oposed to showing the correct tile based on the number in the XML file). 

 

So, this is my blog of doing all the XML walkthrough stuff in a blank project, without any of the other code or anything else confusing me.  It's also sort of a tutorial, so follow it if you like.  It may not be the best way of doing the thing I am trying to acheive, but I will try and explain what I am doing as I go along. 

 

 

Wizards 2.0 Game

I think I’ve gone mad.  I can’t for the life of me work out what I have done wrong here.  The number between each <titlecol> tag gives the tile numer which should be applied to the tile when it loads.  There are three tiles, tile0 (blank), tile 1 (the 2x2 blocks you can see in the image with grass on the top) and a third tile, tile 2 (a 2x2 block of the same tile without brown on). The ordering of the <tilecol> tags determines where the tiles in that row go, and the different <tilerow> determines on what row it’s column’s tiles go.

 

 

(above: the level design)

<map>

<tilerow>

 

<tilecol>1</tilecol>
<tilecol>2</tilecol>
<tilecol>1</tilecol>
<tilecol>2</tilecol>
<tilecol>1</tilecol>
<tilecol>2</tilecol>
<tilecol>2</tilecol>
<tilecol>2</tilecol>
<tilecol>2</tilecol>
<tilecol>0</tilecol>
<tilecol>0</tilecol>
<tilecol>0</tilecol>
<tilecol>0</tilecol>
<tilecol>0</tilecol>
<tilecol>0</tilecol>
<tilecol>0</tilecol>
<tilecol>0</tilecol>
<tilecol>0</tilecol>


</tilerow>

 

the xml code (sample):

 

 

 

 

 

(above: the three different tiles)

 

If it was that somehow the tile 1 tiles were obscuring the tile 2 tiles, being sized wrong or something then I could  understand this, but I tested it by making the tiles on the top row ‘1,2,1,2,1,2,2,2,2’ and when I run the game it is plainly obvious that there is nothing there, it’s not putting a block down!

 

I don't know why I think writing a blog about it will help, but I may realize something stupid I have missed.

 

Well I havn't yet.  Anyway I have lots more stuff to add to the blog, loads more screen shots and things, which I will get around to doing eventually.

 

(note: I am using Adobe Contribute CS3 to edit this blog.  I previously tried using Microsoft Word which DOES have the ability to edit blogs, but I couldn't get it to upload images, and I found that other people had this problem by googling my problem.  However, I am having the same problem with Adobe Contribute although I can't see anything on the internet about similar problems).


Friday, July 18, 2008

PHP (4) - Sorting By Date

PHP & MYSQL TUTORIAL/PROGRESS BLOG


Comments/Guest Book

PART 4 "Sorting By Date"



The next thing I wanted to do was to be able to sort the information backwards, so the latest items of data appear at the top. Although I realized this would be possible to do by simply doing a descending sorting of the ID, I thought it would be more useful to sort descending by date as this is another piece of information that would be useful to provide on a comments page/guest book, etc.

Adding Date field into database table

This is done by going back into the phpMyAdmin front end and clicking the structure tab. Underneath the table is a bit that says Add (number) field(s) At End of Table/At Beginning of Table/After (field name). Since it is more organized to keep the ID as the first field, choose After, and the field name you want it to be after (ID in this case). Name the field 'Date' and select type as 'Date' too. Save this then go back to the php file.

Writing the date into the database

All you need to do in the php is add 'Date' into the list of fields you are adding to and 'CURDATE()' as its associated value. The line should look like this:

$query = "INSERT INTO example1 (Date, Name, Subject, Comment, URL) VALUES (CURDATE(), '$Name', '$Subject', '$Comment', '$URL')";


Save the file and open it from within Firefox. Press submit and then if no errors appear, go back into phpMyAdmin and click the Browse tab, where you should see the date stored in the most recent Id's date field (click ID to make the ID list descending so the newest is at the top).




Information/help from:

page resource
electric toolbox
Tiz Taz

©Chris Guiblin 2008
URL: www.guiblin.com/chris/
EMAIL: chris@guiblin.com

Thursday, July 17, 2008

PHP (2) - MySQL Database

PHP/MYSQL TUTORIAL/PROGRESS BLOG


Comments/Guest Book


Xampp phpMyAdmin
One thing I like about XAmpp is the built version of phpMyAdmin, which is an easy to use front end for MySQL. This can be accessed by going to "http://localhost/xampp" and following the link to phpMyAdmin under the tools section of the left hand navigation, on the XAmpp front page (http://localhost/phpMyAdmin).

CREATING A NEW DATABASE
A new database can be created easily using the Create new database field:


CHOOSING TABLE NAME AND NUMBER OF FIELDS
I have named my database "test1", on the next page choosing "example1" as the new table on the database. I chose five for the Number of fields (different bits of information that will be entered into the table). When creating a database it is best to plan what information is going to be entered into the table and entering the Number of fields accordingly. Both the database and table name should be relevant to what it is going to be used for so you can remember what is what when you have multiple databases and tables.

FIELD NAMES, TYPES AND LENGTHS

For this Database table I chosen field names which would be used on a comments page or guest book; Name, Subject, Comment and URL, as well as ID which will be the comments number (1 for the first comment, 2 for the second, etc). I have set the field type for ID to INT, with the others as VARCHAR. For the Length/Values, I have chosen numbers which I think will be about right for these field inputs.

I have also chosen for the ID field to be set to 'Primary' and 'auto-increment', which makes it the primary field as well as automatically increasing the number in the field as required for the ID field. Choose the Collation you want (chosing none defaulted to latin1_swedish_ci for me, so I chose to use ucs2_bin).



CONNECT TO DATABASE WITH PHP
Now to the coding. Bring up your text editor and enter the following:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');

$dbname = 'test1';
mysql_select_db($dbname);
?>
Things you may have changed which may be causing you problems: If you have set up a username and password for your database, change these accordingly under "$dbuser = " and "$dbpass = ". Also, if you didn't call your database "test1" then type whatever you did call it under "$dbname = ". Also ensure there are ";"'s at the end of every line where it is needed.

Save this file as a php file (I named mine connectphp.php) in C:\xampp\apache\htdocs (or the relative location if you put it somewhere else). Access the page in your web browser (http:\\localhost\connectphp.php in my case) and it should be blank, which is a good sign that it hasn't caused an error.


Information/help from:

Collin Jensen
php.net
php mysql tutorial



©Chris Guiblin 2008
URL: www.guiblin.com/chris/
EMAIL: chris@guiblin.com

PHP (1) - Hello World

PHP & MYSQL TUTORIAL/PROGRESS BLOG

Comments/Guest Book

PAGE 1 "HELLO WORLD"



Introduction


For this tutorial bog I am using Xampp running all the available services included with it on a home computer not running as a web server. Most of the information is going to be the same whether or not you are using Xampp. One thing to note is that not all webspace providers support php and mysql. If you are using a service like this, check whether php and mysql are supported with them before attempting any sort of php /mySQL project.

This tutorial is as much a documentation of what I am doing than teaching how to do it. Although I have some previous experience with web servers, programming and a very small amount with PHP and mySQL, this is a learning experience for me, I just thought it might be useful to write how I am doing it, for anyone else who might be attempting this and has come across this page. If you spot anything wrong then please send a comment or email me and I will check it out.

DOWNLOAD AND INSTALLATION (windows)

Firstly, install XAMPP from
http://www.apachefriends.org/en/xampp.html. I first tried the ZIP file
and tried installing the windows version on my computer. However this
failed, I think because I am using vista and the version wasn't made
for that. So probably best using the installer. Follow the installation
(don't install to program files if in vista, as it will tell you),
enabling the services you want. You must enable php for the above to
work. I have installed everything as I will be dabbling with mysql and
possibly other services later on.





VIEWING/EDITING THE INDEX PAGE



In your web browser go to "http://localhost". This brings up
the yellow and orange xampp page with information and demos, etc. This
will take you to "http://localhost/ampp". Change it to
"http://localhost/index.html to view the index page, which will display
the text "It works!"




To get to where this page is actually stored in your computer,
go to the directory where you installed Xampp ("C:\Xampp" in my case).
You should see a folder named "htdocs". This is where the pages are
stored which will actually be accessible through the web server. In
here you will find a file "index.html", which is the page displayed
when you go to "http://localhost/index.html".




To edit the content of the page, open the file with notepad,
dreamweaver, or any other text editor/web design software. If you don't
understand any of what has come up, you should probably go searching
Google for help or buy a book on basic html. All you need to do to
change the text on the page is to change the text between the tag




Once You have done this, save the text file and reload the page in your browser to display the change.



PHP

Since PHP works differently to html, we will need to change
the file in a few ways to make it work using php. Php in itself is not
built into browsers like html is, therefor it is up to the server to
deal with the php code, and that is why php needed to be installed as a
service earlier.


To create a php document, you must start with "<h&gt;" to show that this is the end of the php code.

To create the words "Hello World" or "It works!" you use
the command "echo" which just means to display the value of something.
In this case you just want to display a string value, so you just need
to type the following:

<?php
echo "Hello";
?>
notes: you must put ";" at the end of echo "Hello" to show
that this is the end of the line of code, and to allow the action to be
performed.



Information/help from:

Collin Jensen
php.net
php mysql tutorial


©Chris Guiblin 2008
URL: www.guiblin.com/chris/
EMAIL: chris@guiblin.com

Sunday, March 16, 2008

Linux

One thing my games tutor Brad suggested was learning Linux and C++, both which are useful things to know and understand. Both of which I have actually wanted to know for a long time.

Strangely enough I had actually downloaded a version of Linux a week or so back, openSuSE 10.4. My Dad and I had previously experimented with this distribution of Linux back at versions 6.4 and then again at 8.0. We had always had problems with the operating system, never quite working properly. However, since I had been ill over the weekend and stuck up in my room and bored I decided to get Linux installed on my barely used laptop. After having some difficulties with swap partitions and the boot record (I had managed to mess the hard drive up some how) I managed to install the operating system and everything has worked perfectly from then. All the hardware compatibility issues I had found with previous versions were gone, and I am very happy with the system, and my laptop is at last getting use again.

While exploring the installed programs included with the OS and the other software on the disk I came across a program under development called qt designer. Bored, and having no idea what it was I opened it and found it was a widget maker. This uses C++ as the language for programming these widgets. I have worked my way through a couple of the basic tutorials, managing to get "hello world" and similar stupidly basic examples working. Hopefully as I continue with this I will learn C++ (which seems very similar to the actionscript I was using in my Flash Game project, so hopefully this won't be too hard).

So not only am I learning Linux and C++, I am learning C++ in Linux. I am also playing the Curse of Monkey Island which has nothing to do with anything, but its fun! (apparently using ScummVM this can be run on Linux, which if I was doing would actually tie in to this post but....I'm not.) :)

Also working on my website, started from scratch again. I wouldn't like to think about how many times I have done this. I guess its because I never really spend all that much time and effort making it look how I want, so whenever I come back to it I don't like it. Anyway I'm keeping it simple for now and will upload soon and hopefully put stuff on it. I keep writing about it in my posts so that when I read them back I will feel guilty and get on with it :P

The fact I have been posting so much lately shows how bored I am lately! The next thing I need to do for my course is get hold of Unreal Tornament 2003 (think thats the version I need) and a book on the game engine as we will be designing a level for it next term, which I am looking forward to but can imagine will be quite difficult so I should really get learning it now!


web pages I looked at and used to fix my hard drive issues in linux:

http://linuxhelp.blogspot.com/2005/11/how-to-repair-corrupt-mbr-and-boot.html
http://www.yolinux.com/TUTORIALS/LinuxTutorialAdditionalHardDrive.html
http://www.tuxfiles.org/linuxhelp/mounting.html
http://ubuntuforums.org/archive/index.php/t-33858.html

Friday, March 14, 2008

Further Flash Programming

Since working on the flash game project I have regained mhy interest in programming and am learning further about actionscript and programming in general.

I am currently working on understanding object movements and the maths behind the movement of objects. Using the code from a reply to a message in a forum (http://www.kirupa.com/forum/showthread.php?p=2297490) I have created a simple movement of a block which moves where you click the mouse.

The object does not stop when it reaches where the player clicked, however. Although I will experiment into how to make it stop when it does reach the location, I also think the block continuing to move would make a good little game if it were to bounce on the walls or to loop back round the other side, or give game over if you go off the side (probably the easiest method for now). By adding objects to collect and avoid this could be a nice quick little game.

Link: http://www.fileden.com/files/2007/11/6/1567526/2.swf

Wednesday, March 05, 2008

Actionscript 3.0 Smooth character movement

Smooth Character Movement
In actionscript 3.0 when you program an object to move following a keypress, the object moves once then pauses before continue the moment. This is the way I have achieved smooth movement, not certain its the best or easiest way but anyway heres what I did:

Using the example of moving left

Under your 'keydown' function for the left key, type mLeft = true;
Then under your 'enterFrame' function, have an if statement saying:

if (moveLeft) {
myCharacter.x = myCharacter.x - 10;
}


Then, under your 'keyup' function for the left key, type mLeft = false;

You will need to define the following variables for the different keys:

var moveLeft:Boolean = false;
var moveRight:Boolean = false;
var moveUp:Boolean = false;
var moveDown:Boolean = false;

(the last two if you are moving the character up and down as well as left and right)

All the code:

//Defining the variables
var moveLeft:Boolean = false;
var moveRight:Boolean = false;
var moveUp:Boolean = false;
var mDown:Boolean = false;


//Adding Event listeners
stage.addEventListener(KeyboardEvent.KEY_UP, reportKeyUp);
stage.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown);
stage.addEventListener(Event.ENTER_FRAME, EnterFrame);

//KeyDown function
function reportKeyDown(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.LEFT) {
moveLeft = true;
}
if (event.keyCode == Keyboard.RIGHT) {
moveRight = true;
}

if (event.keyCode == Keyboard.UP) {
moveUP = true;
}
if (event.keyCode == Keyboard.DOWN) {

moveDOWN= true;
}
}

//Key Up Function
function reportKeyDown(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.LEFT) {
moveLeft = false;
}

if (event.keyCode == Keyboard.RIGHT) {
moveRight = false;
}
if (event.keyCode == Keyboard.UP) {
moveUP = false;
}

if (event.keyCode == Keyboard.UP) {
moveDOWN = false;
}
}

//Enter Frame Function (this happens over and over repeatedly)
function EnterFrame(event:Event):void {
if (moveLeft){
myCharacter.x -= 10;
}
if (moveRight){
myCharacter.x +=10;
}

if (moveUp){
myCharacter.y -=10;
}
if (moveDown){
myCharacter.y +=10;
}

}
}

I *think* that this should work, if it doesn't I apologise and please comment and tell me what the error says or what is happening.