基本上,当我按某个箭头键向某个方向移动时,我的三角形会移动,但是在我松开键之后,我就停止了。我想加速然后松开键,让三角形以相同的速度加速无限的时间。这是我的相关代码:
var x = 0;
var y = 0;
var rotationDegrees = 0;
var movementRate = 5;
var rotationRate = 5;
function draw(){
context.fillStyle = "rgb(0, 0, 0)";
context.fillRect(0, 0, width, height);
drawTriangle(context, x, y, rectWidth, rectHeight, rotationDegrees);
if (rotationDegrees > 360){
rotationDegrees = 0;
}
window.requestAnimationFrame(draw);
}
window.requestAnimationFrame(draw);
window.addEventListener('keydown', function(event) {
console.log('this is where I describe the log: keydown event.which', event.which);
switch(event.which){
case 37:
console.log('left');
rotationDegrees = rotationDegrees - rotationRate;
break;
case 38:
console.log('up');
x = x + movementRate * Math.cos(rotationDegrees * Math.PI / 180);
y = y + movementRate * Math.sin(rotationDegrees * Math.PI / 180);
break;
case 39:
console.log('right');
rotationDegrees = rotationDegrees + rotationRate;
break;
case 40:
console.log('down');
x = x - movementRate * Math.cos(rotationDegrees * Math.PI / 180);
y = y - movementRate * Math.sin(rotationDegrees * Math.PI / 180);
break;
default:
}
});
function drawTriangle(context, x, y, rectWidth, rectHeight, rotationDegrees){
context.save();
var centerX = x + rectWidth/2;
var centerY = y + rectHeight/2;
context.translate(centerX, centerY);
var radians = rotationDegrees * (Math.PI/180);
context.rotate(radians);
context.strokeStyle = 'red';
context.beginPath();
var triangleOriginX = rectWidth/2;
var triangleOriginY = rectHeight/2;
context.moveTo(-triangleOriginX , -triangleOriginY);
context.lineTo(-triangleOriginX + rectWidth, -triangleOriginY + rectHeight/2);
context.lineTo(-triangleOriginX, -triangleOriginY + rectHeight);
context.closePath();
context.stroke();
context.restore();
答案 0 :(得分:0)
在您的关键事件处理程序代码中,使用代码设置delta值替换用于设置app/heroes/index.ts
和x
的代码。然后使用这些增量在主循环更新y
和x
中。否则,只有在按下(正确)键时才会更新位置。
y
然后在循环中:
// ...
case 38:
dx = movementRate * Math.cos(rotationDegrees * Math.PI / 180);
dy = movementRate * Math.sin(rotationDegrees * Math.PI / 180);
// ... etc.
您当然必须在此处实施一些检查和平衡,并声明function draw(){
x += dx;
y += dy;
// ...rest of code
和dx
。