将正方形向某一点旋转
Rotating a square towards a certain point
我正试图使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)
有了这些信息,我认为你可以走得更远。
演示小提琴
相关文章:
- 知道为什么我的旋转木马不会自动更改图片吗
- 如何做到这一点,使代码在不传递条件后执行函数
- 一点javascript元编程&可链接的设置器
- 顺时针旋转Svg元件
- 将鼠标旋转限制为特定的度数
- 旋转后拖动对象
- 禁用旋转木马中的下一个按钮和上一个按钮
- gmap3如何做到这一点-它显示圆圈的任何事件
- 硒元素在这一点上是不可点击的
- 手动创建旋转活动指示器
- 如何在容器中定位旋转的图像
- 在轴上旋转SVG图像
- 绕z轴旋转时出现iOS陀螺仪错误
- 旋转按钮[HTML][JS]
- 在JS中围绕旋转对象旋转对象
- Threejs-围绕中心旋转对象
- 旋转木马;启用内容安全策略时无法工作
- 如何在使用Kinetic拖动同一对象后,在旋转动画中保持先前的偏移
- 菜单切换时箭头旋转
- 将正方形向某一点旋转