I'm making a game and I want to move an element (which would actually be the character) to wherever I click on the page. (mousedown actually)
I believe it's possible with a script that changes an element's position on mousedown but I don't know how to do it.
I need a simple working example and then I'll figure out how to adapt it to my site but I haven't b开发者_开发技巧een able to find one.
I tried some simple moving, and found out a tutorial on how to move it with the keyboard but it's not quite what I want and couldn't find how to do it with the mouse.
I'm testing it here, though I'm chaning the code fast and most of the time nothing is working: http://chusmix.com/game/movechar.php
Some advice, code, link anything will be welcomed. Thanks
Here you go:
HTML:
<div id="area">
<img src="http://placekitten.com/80/80" id="character">
</div>
JavaScript:
var area = $('#area')[0];
character = $('#character')[0];
$(area).click(function(e) {
if ( e.target !== this ) { return; }
var charWidth = $(character).width(),
max = $(this).width() - charWidth,
x = e.offsetX - charWidth/2,
y = e.offsetY - charWidth/2;
$(character).css({
left: x < 0 ? 0 : x > max ? max : x,
top: y < 0 ? 0 : y > max ? max : y
});
});
Live demo: http://jsfiddle.net/WUjKM/2/show/
Btw, I know it's jQuery :/
. If you require a non-jQuery solution, let me know, and I'll rewrite it.
I managed to pull it off only with javascript:
<html>
<head>
<script type="text/javascript">
function showCoords(evt){
document.getElementById("character").style.left = evt.pageX;
document.getElementById("character").style.top = evt.pageY;
}
</script>
</head>
<body onmousedown="showCoords(event)">
<div id="character" style="position: absolute; top: 100px; width: 80px; height: 40px; background:black;"> Char </div>
</body>
</html>
Thanks for all answers
精彩评论