将正方形向某一点旋转

Rotating a square towards a certain point

本文关键字:一点 旋转 正方形      更新时间:2024-02-22

我正试图使shooter0朝着角色旋转(角色将不断移动)。我试着使用atan(),然后将其转换为一个角度,但shooter0不会旋转。

var shooter0 = document.getElementById('shooter0');
var character = document.getElementById('character');
var tracker0 = shooter0.getContext('2d');
// The cordinates for the character and shooter0
var characterLeft = 530;
var characterTop = 180;
var shooter0Left = 960;
var shooter0Top = 470;
while (characterLeft >= 700){
  setInterval(startShooter, 1000);
}

function startShooter(){
  //Getting all the variable to be able to calculate the angle of the hypotenuse
  var dX = characterLeft - tracker0Left;
  var dY = characterTop - tracker0Top;
  var arcTan = Math.atan(dX/dY)* 180/Math.PI;
  var cx = shooter0.width/2;
  var cy = shooter0.height/2;

  tracker0.save();
  tracker0.translate(cx, cy); // pivot point
  //rotating the square towards the character
  tracker0.rotate(arcTan * Math.PI/180);
  //Drawing the square
  tracker0.fillRect(400, 300, 100, 100);
  tracker0.restore();
}

HTML:

<canvas id="character" height="50px;" width="50px;"></canvas>
<canvas id="shooter0" height="100px;" width="100px;"></canvas>

和CSS:

#character{
  position: absolute;
  top: 180px;
  left: 530px;
  border: 3px solid black;
  background-color: orange;
}
#shooter0{
  position: absolute;
  left: 960px;
  top: 470px;
  border: 2px solid black;
  background-color: #B40404;
}

如果您发现代码相当混乱,很抱歉。如果你觉得有用的话,这里有一个我所有代码的小提琴。https://jsfiddle.net/Snubben/tc0j4psz/3/请不要使用任何JQuery。

由于某种原因,我无法让你的小提琴工作,所以我创建了一个小示例。

我在你的代码中注意到的东西:

var arcTan = Math.atan(dX/dY)* 180/Math.PI;:Math.atan返回一个以弧度为单位的角度。然后通过180/Math.PI 将其转换为度数

只是在这里再次将其转换回弧度:tracker0.rotate(arcTan * Math.PI/180);

然后,对于计算角度(以弧度为单位),我认为Math.atan2是最容易使用的:Math.atan2-MDN

Math.atan2用于计算两点之间的角度的用法为:Math.atan2(point2.y - point1.y, point2.x - point1.x)

有了这些信息,我认为你可以走得更远。

演示小提琴