我试图在每个关卡开始时向我的打砖 block 游戏添加方向向量,以便玩家可以朝特定方向射球。
我创建了一个新文件来绘制和更新矢量,但我找不到更新它以使其随光标移动的方法。
目前我的游戏将在垂直位置绘制矢量。我想要做的是创建一个事件监听器,在每次更新时保存鼠标的 x 和 y 位置,然后根据垂直向量与使用 x 和 y 位置制作的向量之间的 Angular 差来旋转向量鼠标。
这是我在矢量文件中绘制的简单箭头。
draw(ctx) {
ctx.save();
ctx.translate(this.paddleCenter.x, this.paddleCenter.y);
ctx.rotate(this.angle * Math.PI/ 180 );
ctx.beginPath();
ctx.strokeStyle = 'red';
ctx.fillStyle = 'red';
ctx.lineWidth = 2;
ctx.moveTo( 0, 0 );
ctx.lineTo( this.pointer.x , this.pointer.y );
ctx.lineTo( this.pointer.x - 10, this.pointer.y + 10);
ctx.arcTo( this.pointer.x, this.pointer.y, this.pointer.x + 10, this.pointer.y + 10, 20);
ctx.lineTo( this.pointer.x, this.pointer.y);
ctx.stroke();
ctx.fill();
ctx.restore();
}
在一个单独的文件中,我有所有的事件监听器。我知道它应该看起来像这样:
document.addEventListener('pointerover', (event) => {
vector.moveVector(event.clientX, event.clientY);
})
哪里
moveVector(x, y) {
this.pointer.x = x;
this.pointer.y = y
}
但它不会在游戏中更新。我想这是因为我的游戏更新功能在达到下一个级别之前不会重新绘制游戏中的对象。
我需要在向量 update(deltaTime) 函数中包含什么,以便向量随鼠标移动?我走在正确的轨道上吗?还是有更好的方法让它发挥作用?
<小时/>更新
我能够让它工作。
在 input.js 中
document.addEventListener('pointerdown', (event) => {
game.vector.mousePointer.x = event.clientX;
game.vector.mousePointer.y = event.clientY;
});
在向量.js 中
update(deltaTime) {
this.angle = this.moveVector();
}
moveVector() {
//Calculate angle to rotate vector
// 0 angle denotes arrow pointing left
let gameY = this.paddleCenter.y;
let gameX = this.paddleCenter.x;
let mouseY = this.mousePointer.y;
let mouseX = this.mousePointer.x;
let theta = 0;
if (this.mousePointer.x < this.paddleCenter.x && this.mousePointer.y < this.paddleCenter.y){
theta = Math.atan((gameY - mouseY) / (gameX - mouseX)) * 180 / Math.PI; };
else if (this.mousePointer.x > this.paddleCenter.x && this.mousePointer.y < this.paddleCenter.y){
theta = 180 - Math.atan((gameY - mouseY) / (mouseX - gameX)) * 180 / Math.PI; };
else if (this.mousePointer.x < this.paddleCenter.x && this.mousePointer.y > this.paddleCenter.y ) {
theta = 0 };
else if (this.mousePointer.x > this.paddleCenter.x && this.mousePointer.y > this.paddleCenter.y) {
theta = 180 };
return theta
};
但是,我目前正在解决更多问题。
我无法仅使用事件监听器上的指针来使向量指向。当我使用“pointerover”时,矢量指向鼠标在屏幕上返回的方向。如果我在实际游戏屏幕上移动鼠标,它不会自动更新。
此外,我绘制的矢量的箭头不旋转。因此,当我在屏幕上按下鼠标时,矢量的线条部分将旋转到正确的位置,但箭头部分保持不变。
如果您对如何解决这些问题有任何建议,我将不胜感激。
最佳答案
思考这个问题的一种方法是将鼠标坐标视为位置向量。
因此,通过从向量获取 Angular ,您可以使用它来旋转上下文,或根据该 Angular 绘制指针。
var getAngle = function(x, y){
const angle = Math.atan2(y, x)/Math.PI*180;
return (360+Math.round(angle))%360; // corrects for angles between 180 ~ 360
}
// you can plug in the mouse coordinate in this
getAngle(-10,10); // returns 135
关于javascript - 如何旋转箭头以指向屏幕上的鼠标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61199554/