Solved

jquery how to move a image in 30px increments via arrow keys

Posted on 2010-11-14
12
1,172 Views
Last Modified: 2012-05-10
i found some code and im trying to understand game ideas via jquery
found a great jquery map, im trying to get the little guy to move now via arrow keys and i cant get it right

how can i move him via arrow keys please
http://dragonsworkshop.com/jquery/gobknobb/test1-tilemap.html

im in hopes i can get him to show e,w,s,n directions when he moves too

thank you in advance for any code or help you may provide

<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Test 1: Create Tile Map</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="js/jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">

var map =
[
	"######################################################################",
	"#.                                                                   #",
	"#.Q                                                                  #",
	"# ..                                                                 #",
	"#                                                                    #",
	"#   E      S   N     W                                               #",
	"#  @@@@@ @@@@@ @     @@@@@       @@@@@ @@@@@  @@@@ @@@@@             #",
	"#    @     @   @     @             @   @     @       @               #",
	"#    @     @   @     @@@           @   @@@    @@@    @               #",
	"#    @     @   @     @             @   @         @   @               #",
	"#    @   @@@@@ @@@@@ @@@@@         @   @@@@@ @@@@    @               #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#      @@@@@ @@@@@ @   @ @   @  @   @  @   @                         #",
	"#        @   @   @ @   @ @@  @  @@  @   @ @                          #",
	"#        @   @   @ @@@@@ @ @ @  @ @ @    @                           #",
	"#      @ @   @   @ @   @ @  @@  @  @@    @                           #",
	"#      @@@   @@@@@ @   @ @   @  @   @    @                           #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"######################################################################",
];

$(document).keydown(function(e){
    // Left
    if (e.keyCode == 37) {
      <!-- $("#moveMe").animate({marginLeft: "-=30px"}, {queue:false}); -->
      $("#moveMe_left");
       return false;
    }
    // Top
    if (e.keyCode == 38) {
      $("#moveMe").animate({marginTop: "-=30px"}, {queue:false});
       return false;
    }
    // Right
    if (e.keyCode == 39) {
      $("#moveMe").animate({marginLeft: "+=30px"}, {queue:false});
       return false;
    }
    // Bottom
    if (e.keyCode == 40) {
      $("#moveMe").animate({marginTop: "+=30px"}, {queue:false});
       return false;
    }
});

$(document).ready(function(){

	var table = [];
	for (var y = 0; y < map.length; y++) {
		var row = "<tr>";
		for (var x = 0; x < map[y].length; x++) {
			var img='';
			var t = map[y].charAt(x);
			var touchNS = (y > 0 && t === map[y-1].charAt(x)) ||
				(y < map.length - 1 && t === map[y+1].charAt(x));
			var touchEW = (x > 0 && t === map[y].charAt(x-1)) ||
				(x < map[y].length - 1 && t === map[y].charAt(x+1));
			switch (t) {
				case 'E': // goblin
					cls = "grass";
					img = '<img src="gfx/walk-e.gif" class="goblin" width="30" height="30" />';
					break;
				case 'W': // goblin
					cls = "grass";
					img = '<img src="gfx/walk-w.gif" class="goblin" width="30" height="30" />';
					break;
				case 'N': // goblin
					cls = "grass";
					img = '<img src="gfx/walk-n.gif" class="goblin" width="30" height="30" />';
					break;
				case 'S': // goblin
					cls = "grass";
					img = '<img src="gfx/walk-s.gif" class="goblin" width="30" height="30" />';
					break;
				case 'Q': // goblin
					img = '<img id="moveMe" src="gfx/walk-s.gif" class="goblin"/>';
					break;
				case '.': // stone
					cls = "stone";
					break;
				case ' ': // grass
					cls = "grass";
					break;
				case '#': // wall
					if (touchNS == touchEW) {
						cls = "wall";
					} else if (touchNS) {
						cls = "wallNS";
					} else {
						cls = "wallEW";
					}
					break;
				case '@': // hedge
					if (touchNS == touchEW) {
						cls = "hedge";
					} else if (touchNS) {
						cls = "hedgeNS";
					} else {
						cls = "hedgeEW";
					}
					break;
			}
			row += "<td id=\"t" + y + "x" + x + "\" title=\"x: " + x + " / y: " + y + "\" class=\"" + cls + "\">" + img + " </td>";
		}
		row += "</tr>";
		table.push(row);
	}

	//alert(table.join(""));
	$("body").append("<table id='map'>" + table.join("") + "</table>");

});

</script>
<style type="text/css">

body {
	margin:0;
	border:0;
}

#map {
	width:2130px;
	padding:0;
	margin:0;
	border:0;
	border-collapse:collapse;
}

#map tr td {
	width: 30px;
	height:30px;
	margin:0;
	border:0;
	padding:0;
	border-collapse:collapse;
	border:1px solid red; /**/
}

/* tiles */
.grass {
	background-image:url('gfx/tile-grass.gif');
}
.stone {
	background-image:url('gfx/tile-stone.gif');
}
.hedge {
	background-image:url('gfx/tile-hedge.gif');
}
.hedgeNS {
	background-image:url('gfx/tile-hedge-ns.gif');
}
.hedgeEW {
	background-image:url('gfx/tile-hedge-ew.gif');
}
.wall {
	background-image:url('gfx/tile-wall.gif');
}
.wallNS {
	background-image:url('gfx/tile-wall-ns.gif');
}
.wallEW {
	background-image:url('gfx/tile-wall-ew.gif');
}

.goblin {
	<!-- position: absolute; -->
	z-index: -1;
    width: 30px;
    height: 30px;
    vertical-align: botom;
    margin:-3px;
	<!-- left: 0; -->
	<!-- top: 0; -->
}
    #moveMe{
      <!-- position: absolute; -->
      position:relative;
      <!-- width: 30px; -->
      <!-- height: 30px; -->
      z-index: -1;
      <!-- left:50%; -->
      <!-- top:50%; -->
      <!-- margin-left:-0px; -->
      <!-- margin-top:-0px; -->
      <!-- background-color:red; -->
    }
    #moveMe_left{
      <!-- position: absolute; -->
      position:relative;
      z-index: -1;
      left:-30px;
      <!-- top:50%; -->
      background-color:red;
    }
</style>
</head>
<body>

<noscript>JavaScript required to view this page.</noscript>
</body>
</html>

Open in new window

0
Comment
Question by:Johnny
  • 7
  • 5
12 Comments
 
LVL 14

Expert Comment

by:ali_kayahan
ID: 34132465
Hi Pern , the code below runs as well , dont forget to tie jquery named as jq below
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="jq.js"></script>
<script>
	var left,top,right,bottom ;
	$(function(){
		$('body').keydown(function(e){
			switch(e.keyCode){
				case 37 :
					left = parseFloat($('#littleMan').css('left')) ;
					$('#littleMan').css('left',(left - 10) +"px") ;
				break;
				case 38 :
					top = parseFloat($('#littleMan').css('top')) ;
					$('#littleMan').css('top',(top - 10) +"px") ;
				break;
				case 39 :
					right = parseFloat($('#littleMan').css('left')) ;
					$('#littleMan').css('left',(right + 10) +"px") ;
				break;
				case 40 :
					bottom = parseFloat($('#littleMan').css('top')) ;
					$('#littleMan').css('top',(bottom + 10) +"px") ;
				break;	
			}	
		});
	});
</script>
<style>
	#littleMan{
		width:30px;
		height:100px;
		background:#09C;
		position:absolute;
		left:20px;
		top:0px;	
	}
</style>
</head>

<body>
<div id="littleMan"></div>
</body>
</html>

Open in new window

0
 
LVL 14

Expert Comment

by:ali_kayahan
ID: 34132511
And the logic is that ;
First : you should set position value as absolute from css in order to use left,top,right,bottom properties for your little man .
Second : we start to listen body for keyboard events when document gets ready

$(function(){
   // Those line of codes triggered when document gets ready
   $('body').keydown(function(e){ // we can use css selectors in jquery as they are..
         // when a key is down keydown function is triggered and keycode passed as parameter..
         // we can determine which key is pressed by switching its value , if you alert(e.keyCode) you
        // may get all keycodes that are assigned to keys
       switch(e.keyCode){
           case 37 :
                 // key code of 37 means left arrow , so we should get left property value of item in subject
                // in this case its our little man , and we will minus for ex. 10 to move it 10px left
               var left = parseFloat($('#littleMan').css('left')) ; // this gets left value of little man with px appended to it
                // we should trim px by using parseFloat because we ll use our Nasa math in here..!
                $('#littleMan').css('left',(left - 10) + "px") ; // we should append px after our heavy math job.
           break;
       }
    });
});

thats all when you press left arrow the littleMan ided html element moves left..
0
 

Author Comment

by:Johnny
ID: 34132520
@ali_kayahan
hi again!

things to note.


up arrow does not work in your example
http://dragonsworkshop.com/jquery/gobknobb/little_man.php


i need the image to move its on z-index: -1; as it has an image under it, so how to incorp your example i dont have a clue how to do that.

i have some code in my post for key capture of arrows. just need the guy to move 30 px in each direction, mine moves the margin and not the guy, was experimenting on left arrow keys.

0
Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

 
LVL 14

Expert Comment

by:ali_kayahan
ID: 34132553
Pern , up arrow works as well , i am using ie8 can you please re-check , just append z-index:-1 like ;

<style>
      #littleMan{
            width:30px;
            height:100px;
            background:#09C;
            position:absolute;
            left:20px;
            top:0px;
                           z-index:-1;
      }
</style>

can you please winrar your files with images and i can than add neccessary lines..
0
 

Author Comment

by:Johnny
ID: 34132576
im Google chrome the up arrows not working on this page
http://dragonsworkshop.com/jquery/gobknobb/little_man.php


ill zip up the files for you
on mine
0
 

Author Comment

by:Johnny
ID: 34132586
wont let me add file as rar its small here link
http://dragonsworkshop.com/jquery/gobknobb/gobknobb.rar
0
 

Author Comment

by:Johnny
ID: 34132596
ill be ONE thing IE got right Google Chrome didn't.. confirmed same code works fine in IE and not Google Chrome odd very odd indeed.
(can you tell i hate IE)
0
 

Author Comment

by:Johnny
ID: 34132614
lol the http://dragonsworkshop.com/jquery/gobknobb/test1-tilemap.html page wont load in IE says map is null or empty. LOL i so hate IE it works when it feels like it.
0
 
LVL 14

Expert Comment

by:ali_kayahan
ID: 34132632
I downloaded files and it only works at chrome (: , also arrow keys work fine in your files , whats the issue that are having
0
 

Author Comment

by:Johnny
ID: 34132668
cant get the guy to move it moves the margins not the image
0
 
LVL 14

Accepted Solution

by:
ali_kayahan earned 500 total points
ID: 34132759
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Test 1: Create Tile Map</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="js/jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">

var map =
[
	"######################################################################",
	"#.                                                                   #",
	"#.Q                                                                  #",
	"# ..                                                                 #",
	"#                                                                    #",
	"#   E      S   N     W                                               #",
	"#  @@@@@ @@@@@ @     @@@@@       @@@@@ @@@@@  @@@@ @@@@@             #",
	"#    @     @   @     @             @   @     @       @               #",
	"#    @     @   @     @@@           @   @@@    @@@    @               #",
	"#    @     @   @     @             @   @         @   @               #",
	"#    @   @@@@@ @@@@@ @@@@@         @   @@@@@ @@@@    @               #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#      @@@@@ @@@@@ @   @ @   @  @   @  @   @                         #",
	"#        @   @   @ @   @ @@  @  @@  @   @ @                          #",
	"#        @   @   @ @@@@@ @ @ @  @ @ @    @                           #",
	"#      @ @   @   @ @   @ @  @@  @  @@    @                           #",
	"#      @@@   @@@@@ @   @ @   @  @   @    @                           #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"#                                                                    #",
	"######################################################################",
];

$(document).keydown(function(e){
    // Left
    if (e.keyCode == 37) {
      $("#moveMe2").animate({marginLeft: "-=30px"}, {queue:false});
       return false;
    }
    // Top
    if (e.keyCode == 38) {
      $("#moveMe2").animate({marginTop: "-=30px"}, {queue:false});
       return false;
    }
    // Right
    if (e.keyCode == 39) {
      $("#moveMe2").animate({marginLeft: "+=30px"}, {queue:false});
       return false;
    }
    // Bottom
    if (e.keyCode == 40) {
      $("#moveMe2").animate({marginTop: "+=30px"}, {queue:false});
       return false;
    }
});

$(document).ready(function(){

	var table = [];
	for (var y = 0; y < map.length; y++) {
		var row = "<tr>";
		for (var x = 0; x < map[y].length; x++) {
			var img='';
			var t = map[y].charAt(x);
			var touchNS = (y > 0 && t === map[y-1].charAt(x)) ||
				(y < map.length - 1 && t === map[y+1].charAt(x));
			var touchEW = (x > 0 && t === map[y].charAt(x-1)) ||
				(x < map[y].length - 1 && t === map[y].charAt(x+1));
			switch (t) {
				case 'E': // goblin
					cls = "grass";
					img = '<img src="gfx/walk-e.gif" class="goblin" width="30" height="30" />';
					break;
				case 'W': // goblin
					cls = "grass";
					img = '<img src="gfx/walk-w.gif" class="goblin" width="30" height="30" />';
					break;
				case 'N': // goblin
					cls = "grass";
					img = '<img src="gfx/walk-n.gif" class="goblin" width="30" height="30" />';
					break;
				case 'S': // goblin
					cls = "grass";
					img = '<img src="gfx/walk-s.gif" class="goblin" width="30" height="30" />';
					break;
				case 'Q': // goblin
					//img = '<img id="moveMe" src="gfx/walk-s.gif" class="goblin"/>';
					break;
				case '.': // stone
					cls = "stone";
					break;
				case ' ': // grass
					cls = "grass";
					break;
				case '#': // wall
					if (touchNS == touchEW) {
						cls = "wall";
					} else if (touchNS) {
						cls = "wallNS";
					} else {
						cls = "wallEW";
					}
					break;
				case '@': // hedge
					if (touchNS == touchEW) {
						cls = "hedge";
					} else if (touchNS) {
						cls = "hedgeNS";
					} else {
						cls = "hedgeEW";
					}
					break;
			}
			row += "<td id=\"t" + y + "x" + x + "\" title=\"x: " + x + " / y: " + y + "\" class=\"" + cls + "\">" + img + " </td>";
		}
		row += "</tr>";
		table.push(row);
	}

	//alert(table.join(""));
	$("body").append("<table id='map'>" + table.join("") + "</table>");

});

</script>
<style type="text/css">

body {
	margin:0;
	border:0;
	
}

#map {
	width:2130px;
	padding:0;
	margin:0;
	border:0;
	border-collapse:collapse;
	z-index:-222;
	position:fixed;
}

#map tr td {
	width: 30px;
	height:30px;
	margin:0;
	border:0;
	padding:0;
	border-collapse:collapse;
	border:1px solid red; /**/
}

/* tiles */
.grass {
	background-image:url('gfx/tile-grass.gif');
}
.stone {
	background-image:url('gfx/tile-stone.gif');
}
.hedge {
	background-image:url('gfx/tile-hedge.gif');
}
.hedgeNS {
	background-image:url('gfx/tile-hedge-ns.gif');
}
.hedgeEW {
	background-image:url('gfx/tile-hedge-ew.gif');
}
.wall {
	background-image:url('gfx/tile-wall.gif');
}
.wallNS {
	background-image:url('gfx/tile-wall-ns.gif');
}
.wallEW {
	background-image:url('gfx/tile-wall-ew.gif');
}

.goblin {
	<!-- position: absolute; -->
	z-index: -1;
    width: 30px;
    height: 30px;
    vertical-align:text-botom;
	<!-- left: 0; -->
	<!-- top: 0; -->
}
    #moveMe{
      position:absolute;
      <!-- width: 30px; -->
      <!-- height: 30px; -->
      z-index: 22;
      <!-- left:50%; -->
      <!-- top:50%; -->
      <!-- margin-left:-0px; -->
      <!-- margin-top:-0px; -->
			background:red;
    }
	 #moveMe2{
      position:absolute;
      <!-- width: 30px; -->
      <!-- height: 30px; -->
      z-index: 22;
      <!-- left:50%; -->
      <!-- top:50%; -->
      <!-- margin-left:-0px; -->
      <!-- margin-top:-0px; -->
    }
</style>
</head>
<body>
<img id="moveMe2" src="gfx/walk-s.gif" class="goblin"/>
<noscript>JavaScript required to view this page.</noscript>
</body>
</html>

Open in new window

0
 

Author Closing Comment

by:Johnny
ID: 34133096
thank you very much
0

Featured Post

Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
Styling your websites can become very complex. Here I'll show how SASS can help you better organize, maintain and reuse your CSS code.
In this tutorial viewers will learn how add a scalable full-width header using CSS3. Create a new HTML document with an internal stylesheet. Set a tiled background.:  Create a new div and name it Header. Position it with position:absolute at the top…
In this Micro Tutorial viewers will learn how to create a CSS image sprite (In a later tutorial, viewers will learn how to use CSS and HTML to create a navigation menu using this sprite) Open a new Photoshop document with a width of (Icon width)x(N…

680 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question