javascript - 旋转和移动对象(跟随鼠标) - Javascript
问题描述
大家!
我想做一个小坦克,它会跟随鼠标并将大炮转向鼠标。
我跟着鼠标做了一笔交易,但是我无法将枪对准鼠标。我的代码:
// canvas variable
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// browser window size
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
//set canvas size
canvas.width = windowWidth;
canvas.height = windowHeight;
var mouseX = 0;
var mouseY = 0;
var baseAngle = 1;
class Cannon {
constructor(x,y, angle, size, speed){
this.x = x;
this.y = y;
this.angle = angle;
this.size = size;
this.speed = speed;
}
draw() {
// bullet
ctx.setTransform(1, 0, 0, 1, this.x, this.y - (this.size/2));
ctx.translate(this.x, this.y);
ctx.rotate(baseAngle);
ctx.beginPath();
ctx.rect(this.x, this.y - (this.size/2), this.size*2, this.size);
ctx.fillStyle = 'rgb(192,192,192)';
ctx.fill();
ctx.lineWidth = 3;
ctx.strokeStyle = 'rgba(128,128,128)';
ctx.stroke();
ctx.closePath();
//body
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
ctx.fillStyle = 'rgb(0,96,255)';
ctx.fill();
ctx.lineWidth = 3;
ctx.strokeStyle = 'rgba(128,128,128)';
ctx.stroke();
ctx.closePath();
}
update() {
// mooving
var dx = (mouseX - this.x)*.125;
var dy = (mouseY - this.y)*.125;
var dist = Math.sqrt(dx*dx + dy*dy);
if(dist > this.speed){
dx *= this.speed / dist;
dy *= this.speed / dist;
}
this.x += dx;
this.y += dy;
// rootating
baseAngle = Math.atan2(mouseY - this.y, mouseX - this.x);
}
}
const newCannon = new Cannon(80,60, 1, 20, 7);
onmousemove = function(e){
mouseX = e.clientX;
mouseY = e.clientY;
}
function gameUpdate() {
ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
ctx.clearRect(0, 0, canvas.width, canvas.height);
newCannon.draw();
newCannon.update();
requestAnimationFrame(gameUpdate);
}
gameUpdate();
<!DOCTYPE html>
<html>
<head>
<title>CRUSH DEMO</title>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
</html>
大炮必须沿鼠标方向旋转(圆圈本身不能旋转)。
帮助我,请修复代码!
解决方案
推荐阅读
- python - 无法对 Pandas 数据框中同名的列执行函数
- python - “从文件导入类”也尝试导入其他类
- javascript - 如何在节点js中将异步转换为同步
- python - Python:拟合线来计算我的数据的减少部分(最大值到最小值)并推断它们(最大值到最大值)?
- c# - 将数据从一列转移到同一张表中的另一列
- rust - IntoHandlerError 未针对列为已实现的类型实现
- python - Wordnet:获取单词的派生相关形式
- discord.js - 如何从我的不和谐机器人中删除代码?
- eclipse - 在 Eclipse 中运行机器人测试用例 - 找不到输出控制台
- html -