Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/88.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 向某一点旋转正方形_Javascript_Html_Css_Rotation - Fatal编程技术网

Javascript 向某一点旋转正方形

Javascript 向某一点旋转正方形,javascript,html,css,rotation,Javascript,Html,Css,Rotation,我试图使射击手0朝角色旋转(角色将不断移动)。我尝试使用atan(),然后将其转换为一个角度,但shooter0不会旋转 var shooter0 = document.getElementById('shooter0'); var character = document.getElementById('character'); var tracker0 = shooter0.getContext('2d'); // The cordinates for the character and s

我试图使射击手0朝角色旋转(角色将不断移动)。我尝试使用
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:

很抱歉,如果您发现代码比较混乱。如果你觉得有用的话,这里有我所有的代码。
请不要使用任何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
计算两点之间的角度为:
Math.atan2(point2.y-point1.y,point2.x-point1.x)

有了这些信息,我想你可以走得很远

<canvas id="character" height="50px;" width="50px;"></canvas>
<canvas id="shooter0" height="100px;" width="100px;"></canvas>
#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;
}