Ema*_*gux 1 javascript jquery html5 canvas
我正在编写一个带有JQuery和HTML5画布标签的简单页面,我在画布上移动一个形状,按'w'表示向上,'s'表示向下,'a'表示左,'d'表示右.我把它全部工作了,但我希望这个形状在敲击钥匙时以恒定的速度开始移动.现在有某种保持期,然后运动开始.如何让动作立即发生?
这是我的代码的重要部分:
<script src="jquery.js"></script>
<script src="JQuery.print.js"></script>
<body>
<canvas id="myCanvas" width="500" height="200" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<br><br>
start navigating<input type="text" id = "enter"/>
<div id = "soul2">
coords should pop up here
</div>
<div id = "soul3">
key should pop up here
</div>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
//keypress movements
var xtriggered = 0;
var keys = {};
var north = -10;
var east = 10;
var flipednorth = 0;
$(document).ready(function(e){
$("input").keydown(function(){
keys[event.which] = true;
if (event.which == 13) {
event.preventDefault();
}
//press w for north
if (event.which == 87) {
north++;
flipednorth--;
}
//press s for south
if (event.which == 83) {
north--;
flipednorth++;
}
//press d for east
if (event.which == 68) {
east++;
}
//press a for west
if (event.which == 65) {
east--;
}
var msg = 'x: ' + flipednorth*5 + ' y: ' + east*5;
ctx.beginPath();
ctx.arc(east*6,flipednorth*6,40,0,2*Math.PI);
ctx.stroke();
$('#soul2').html(msg);
$('#soul3').html(event.which );
$("input").css("background-color","#FFFFCC");
});
$("input").keyup(function(){
delete keys[event.which];
$("input").css("background-color","#D6D6FF");
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
如果我不想发布这么长的代码,请告诉我.
nnn*_*nnn 10
你缺少的是一个"游戏循环".
在决定是否以及何时在画布周围移动形状时,您需要使用键事件来跟踪在任何给定时刻哪些键已关闭,而不是直接响应键向下或向上,然后检查键的状态.setTimeout()基于关键事件的基于循环的循环运行.
您已经开始使用keys变量来跟踪给定键是否随时关闭:
// in keydown
keys[event.which] = true;
// in keyup
delete keys[event.which];
Run Code Online (Sandbox Code Playgroud)
...除了event未定义之外 - 您需要将其作为事件处理程序的参数,并且您的代码中没有任何代码实际检查过这些值keys.
这是我正在谈论的简化版本:
$(document).ready(function(e){
var keys = {};
$("input").keydown(function(event){
keys[event.which] = true;
}).keyup(function(event){
delete keys[event.which];
});
function gameLoop() {
// w for north
if (keys[87]) {
north++;
flipednorth--;
}
//press s for south
if (keys[83]) {
north--;
flipednorth++;
}
// etc. for other keys
// code to move objects and repaint canvas goes here
setTimeout(gameLoop, 20);
}
gameLoop();
});
Run Code Online (Sandbox Code Playgroud)
演示:http://jsfiddle.net/ktHdD/1/
该gameLoop()函数将运行大约20毫秒左右(您可以根据需要改变它,但这足够快,以便合理平滑的动画).每次运行时,它会检查是否有任何键是关闭的,如果是,则调整相关的位置变量和重新绘制.如果你有其他自动移动的物体(例如,在游戏中可能有坏人),你也可以在gameLoop()功能中更新它们.
| 归档时间: |
|
| 查看次数: |
3435 次 |
| 最近记录: |