[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

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

Posted on 2010-11-14
12
Medium Priority
?
1,197 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
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.

 
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 2000 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Browsers only know CSS so your awesome SASS code needs to be translated into normal CSS. Here I'll try to explain what you should aim for in order to take full advantage of SASS.
A while back, I ran into a situation where I was trying to use the calculated columns feature in SharePoint 2013 to do some simple math using values in two lists. Between certain data types not being accessible, and also with trying to make a one to…
In this Micro Tutorial viewers will learn how to create navigation buttons that change on rollover, using CSS (Continuation of the CSS Image Sprite tutorial) Create a parent ID for all the list items       - Specify position: absolute and display: block…
In this tutorial viewers will learn how to customize the background color and font color of highlighted text using the ::selection element in CSS Begin by defining the selected text as an element in CSS by typing "::selection": Style the ::selection…

650 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