• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1201
  • Last Modified:

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

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
Johnny
Asked:
Johnny
  • 7
  • 5
1 Solution
 
Ali KayahanFull Stack DeveloperCommented:
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
 
Ali KayahanFull Stack DeveloperCommented:
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
 
JohnnyAuthor Commented:
@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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
Ali KayahanFull Stack DeveloperCommented:
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
 
JohnnyAuthor Commented:
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
 
JohnnyAuthor Commented:
wont let me add file as rar its small here link
http://dragonsworkshop.com/jquery/gobknobb/gobknobb.rar
0
 
JohnnyAuthor Commented:
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
 
JohnnyAuthor Commented:
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
 
Ali KayahanFull Stack DeveloperCommented:
I downloaded files and it only works at chrome (: , also arrow keys work fine in your files , whats the issue that are having
0
 
JohnnyAuthor Commented:
cant get the guy to move it moves the margins not the image
0
 
Ali KayahanFull Stack DeveloperCommented:
<!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
 
JohnnyAuthor Commented:
thank you very much
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 7
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now