Last Good Quote: Son's are the seasoning on our lives. - Someone on Facebook

Monday, November 24

Javascript - Move that Image

Another Code Report,

How to move an image to another place on the screen. The user picks the location by clicking the mouse somewhere within the window.

This builds on the last code base, which featured the mouse Position finder code.

Watch It In Action (View source to get the code)

A couple of notes to keep in mind:
  • You can only click once, then you have to wait for it to get to it's destination
  • log() - Puts a message in the div, a cheap debugging technique
  • move() - The meat! What we call a re-cursive function, is called again and again until the object reaches its destination
  • findPos() - returns the position of an object, this is actual a cheater function as it does not get the true position of an object. (see mobLib for the full function)
I purposely did not comment well, if you need to have comments for these simple functions, you may want to get something a bit easier to work with. (my 2 cents)


var speed = 1;
var moving = false;
function mouseClicked(e)
{
if(!moving)
{
pos = getMousePos(e); //from included js file
moving = true;
move("player", pos[0],pos[1]);
log("Clicked: " + pos[0] + "," + pos[1]);
}
else
{
log("Object is in the process of moving.");
log("Click refresh to start over.");
}
}

function log(msg)
{
document.getElementById("log").innerHTML = msg + "
" + document.getElementById("log").innerHTML;
}


function move(objID, destX, destY)
{
var obj = document.getElementById(objID);
var pos = findPos(objID);

currentX = pos[0];
currentY = pos[1];
newX = currentX;
newY = currentY;



if(destX > currentX)
{
//log("X:" + destX + " vs CurrentX: " + currentX);
newX+=speed;
}

if(destX <> currentY)
{
newY+=speed;
}

if(destY < top =" newY;" left =" newX;" t =" setTimeout(" moving =" false;" posx =" 0;" posy =" 0;" e =" window.event;" posx =" e.pageX;" posy =" e.pageY;" posx =" e.clientX" posy =" e.clientY" out =" new" obj =" document.getElementById(objectID);" curleft =" curtop" curleft =" obj.offsetLeft" curtop =" obj.offsetTop" onclick =" mouseClicked;">
Some things to try and play with:
  • Can you speed up the movement to the destination?
  • Can you add more images and allow the user to control more than 1?
  • Can you make the image move so that it's center ends up on the destination point? (right now the top left corner ends up there)



Javascript - Finding that mouse position

I seem to constantly need this bit of code. Hope it helps someone else.

The following javascript code, finds the mouse position and returns it in an array.


function getMousePos(e) {
var posx = 0;
var posy = 0;
if (!e) var e = window.event;

if (e.pageX || e.pageY)
{
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY)
{
posx = e.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
var out = new Array(2);
out[0] = posx;
out[1] = posy;
return out;
}


Demo - You can see it in action here.

Credits - I got the basics of this script from here.

Monday, November 3

Tool - Popup builder

An very old bit of code, written before popups were considered a curse.

This tool will allow a user to build their own popup screen and handler.

Again bit old, but I thought I'd put it out there.

View the Tool

Tool - Creating Drop Down Menus

Another experiment for the lab. I got a bit tired of creating those drop down menus by hand, so I built this page to help me create them.

Looking back, I could have built a code snippet or macro to do the same thing, but this was more fun to build.

All HTML and javascript.

Feel free to use and modify for your own use.

Right click and "View Source" to get code.

Drop Down Builder

Code - Javascript Animation

Many moons ago, I wrote this small library package. It handles a number of interactive functions that one might use on a Web 2.0 site.

It's not fully tested but I use parts and pieces of it quite often.

I figure that if anyone else finds it useful they might like to look at it. Especially those new to programming.

The most interesting is an animation function which allows you to set the velocity of a div tag and then watch it zoom around the screen.

Most functions are multi-browser compatible, I think one if IE only though.

Feel free to use for any of your projects. A link would be nice but not mandatory.

Source Available

Thursday, October 30

Path Finding in Javascript

I went back to the Lab (cause I needed to get my mind off the job). I decided to write a path finding algorithm in javascript.

I used my typical map setup. I found some pseudo-code for the A* path finder. I did the best I could (there was a heuristic in that pseudo code that I could not quite duplicate)

Anyway, it seems to work nicely. It does not find the shortest path, but it does find a path.


Feel free to use it for your own usage.

One Note: It uses a recurring function, I limited it to 40 loops. If you have a large map, you may need to up this a bit.

Take a Look

Source Code

Tuesday, September 9

Display All Images in a Directory

The following php code will allow you to display/show all images in a folder. Be careful as if there is an executable file in this folder it will get executed.

(Just cause I'm tired of searching for it every time I want to do it)

$dir=dir("./images/.");
while($filename=$dir->read())
{
if($filename != "."
&& $filename != ".."
&& $filename != ".."
&& $filename != "Thumbs.db" )
{
print $filename . " - ";
}

Tuesday, July 29

Future Books and Dreams

I'm interesting in writing and think that I have a lot to share. (Although my wife and brothers would tell you differently.) Here is a list of books I would like to write and why:

Programming for High School Kids
I currently volunteer time teaching kids in grades 9 - 12 how to build basic web pages in ASP and .Net. I've done that for about 4 years now. I really enjoy doing it and I learn a lot about my development processes each year that I teach. The kids that I teach walk into my class with no computer programming or web design skills and 8 months later they are able to build full scale web applications.

This is done through the BDPA organization with the HSCC program.

Game Building with PHP
A book about how to build web based php game. This would cover some of the newer techniques like AJAX and map display, movement and stats. I also have read a lot of interesting things on game modeling and building addictive games. I think writing this book would be a great learning experience for myself.

Pseudo Auto-biography
I've always wanted to write about my family and my past. I have pretty interesting background, I have 3 brothers and 2 sisters, a white mother, a black father who spent 20+ years in the military, is a vet and a Buddhist. I also was raised in a very religious environment which I broke out of when I got older. I never watched TV or listened to music till I turned about 16. Because of this I can read a 300+ page book in about 2 hours. I've a collection of over 1000 sci-fi books and can remember almost every chapter of all of them. All of this gives me, what I think is a unique view on race, religion, ethics and life in general.

Why I raised my Sons the way I did
I really want to write this one just for my boys. I have a 2 and 9 year old and I think that they would appreciate some insights on why and how I made the choices I am now making in regard to how they are raised. Again I think this book would be educational both for myself and for them, but the most interested reader of this book would be my wife. *grin* Love ya Babe!

Anyway, just a few things that were on my mind. If you feel like it leave me a comment on which one I should start first.

Friday, July 11

Cleaning out the Code Closet

I was going through my PC backups and looking at all those old projects I have out there. It's interesting how much stuff I've worked on "Just for Fun"

I figured I'd list them here so, if you are interested in any of the code let me know. I'm usually happy to share. But keep in mind, these are all projects that I did just to see what can be done, so they are mostly proto-types.

  1. myAI - A php based neural net project, gives a visual display of how an AI neural net works. 95% completed.
  2. Great Browser Based Games - An engine to allow people to post their PBBG games, I did this in an interesting AJAXy way. 75% completed
  3. Card - An RPG card game, wrote in PHP, browser based, currently in Alpha. 99% complete. (No I won't share source on this one)
  4. RPG Game Template - A template that will allow other novice developers to build a web based RPG. 50% completed
  5. mobLIB - My library of javascript functions for moving things around, doing AJAX and other funky stuff.
  6. Monster Football League - A php and javascript based american football game. This was kind of neat, but I ran into some processing problems, evidently trying to calculate the position of 24 players and a football on a 100 yard field is a bit more then javascript can handle. But it was fun to try.
  7. Horse Racing VR - I was collobarating with someone to do a Horse Racing VR game, sadly I got caught up in real life stuff that pulled me off that project and my partner disappeared.
  8. Stock Analyzer - A program that analyzes 3000 stocks and gives you the top 3 - 5 potentials each day. 90% complete, working towards a release. (No source code available on this one)
  9. Blade of a Mage - Another browser based PHP game, I used to run a long time ago. Took it offline because I didn't have the time to manage it...looking at putting it back online.
  10. Star Fighter - A flash game, simple top down plane game. Graphics are ugly as hell, so I didn't deploy it.
  11. Tactics - A flash game, imagine chess, but with RPG characters that have stats and abilities. Completed but took too much effort to maintain code wise (I don't enjoy working with flash). It had a php backend.
  12. Ships - A flash game, this was based on all the PBBG space games out there, except with this one you could see the movement of your ships and what not. Ran it online for a while but it ended up, hogging some server resources.
  13. Worlds of War - An isometric Mech battling game, I loved this game. But some moron hacked it and crippled my server. I fixed the hack but I worry about putting the game back online. (irrational fear, but look at what number it ended up being on the list...13...its a sign I tell you!)
  14. Battle Forces Online - Fully deployed operation game, RPG isometric top down view. I like it but I think it needs a lot of tender love and care to turn it into the real thing.
Well that is my list...of course that's just on this PC, who know what I have on my other one.

Thursday, July 3

Dominating Keyboard Controll in Javascript

A great blogger at Lost Garden, setup a development challenge. The challenge was to build a game incorporating shadows.

While not exactly in line with his rules, I wrote a javascript game. While building this I had to figure out how to move a character around the screen using javascript.

For those who just like to look at code, here is the source and a demo.


I started by placing a div tag which had absolute positioning. This allowed me to move the div around the screen.


<div id="unit"
style="position:absolute;
top:0px; left:0px;
height:20px;width:20px;
margin:0px;padding:0px;"><img src=man.gif width=30 height=30></div>


The next step was to capture any key presses for that div, there are a number of ways to do this but I did it with the following javascript:

controlledObj = document.getElementById("unit");
document.onkeydown = keypressed;


The first line let's me know which div I am controlling, the second line captures all key events to the keypressed function.

The key pressed function watches for arrow keys and moves the controlledObject in the appropriate direction:
function keypressed(event)
{
if(event.type == 'keydown' && event.keyCode == 38)
{
//up
dir="N";
pos = findPosOfObject(controlledObj);
controlledObj.style.top=pos[1]-5;
}

if(event.type == 'keydown' && event.keyCode == 40)
{
//down
dir="S";
pos = findPosOfObject(controlledObj);
controlledObj.style.top=pos[1]+5;
}


if(event.type == 'keydown' && event.keyCode == 37)
{
//west
dir="W";
pos = findPosOfObject(controlledObj);
controlledObj.style.left=pos[0]-5;
}

if(event.type == 'keydown' && event.keyCode == 39)
{
//east
dir="E";
pos = findPosOfObject(controlledObj);
controlledObj.style.left=pos[0]+5;


}
}

There is a special function, findPosOfObject(), used in that bit of code, that gives me the precise location of a div tag. This is something I googled, I'm not sure where it came from but it's a pretty simple piece of code. It looks at an object, goes up the DOM tree to find all its parents and finds the exact top and left of the object. It then returns those values in an array.

function findPosOfObject(obj)
{
var curleft = curtop = 0;
if (obj.offsetParent)
{
curleft = obj.offsetLeft
curtop = obj.offsetTop
while (obj = obj.offsetParent)
{
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
}

return [curleft,curtop];
}




And that is how I moved an object around on the screen.

You can see the end results Shrooms
and the code can be downloaded here.

Enjoy!

Followers