在我的游戏中,你可以点击橙色框(它应该代表一个怪物).单击后,绿色线将附加到字符div.例如,为了更好的解释:

这是我用来生成行的代码:
l = document.createElement('div');
l.innerHTML='<div id="oLineBar" style=" transform: rotate(' + RANDOM + 'deg);" class="fadeIn2"><div id="lineBar" class="lineBarCharacter"></div></div>';
character.appendChild(l);
Run Code Online (Sandbox Code Playgroud)
那个CSS就是:
.lineBarCharacter{
height: 321px;
width: 2px;
background: rgba(39, 182, 0, 0.46)
}
#oLineBar {
position: absolute;
top: 20px;
left: 37px;
opacity: 1;
transition: transform 1s linear;
transform-origin: top left;
transform-style: preserve-3D;
-webkit-transition: opacity 1s;
transition: opacity 1s;
-ms-transition-property: opacity, -ms-transform;
}
Run Code Online (Sandbox Code Playgroud)
现在,我在这里得到了橙色框getboundingClientRect:
ClientRect {height: 95, width: 88, left: 1250.5, bottom: 471, right: 1338.5…}bottom: 471height: 95left: 1250.5right: 1338.5top: 376width: 88
Run Code Online (Sandbox Code Playgroud)
如何根据橙色框所在的位置(来自getboundingClientRect数据)确定正确的旋转度?
不只是特定的橙色框,而是从getBoundingClientRect检索的任何数据.如果这是有道理的......我有点迷茫,如果这令人困惑,请提前对不起.我非常希望那条线与橙色盒子的方向相同.
这更像是一个数学问题而不是编程问题,但您基本上应该计算角色与其目标之间的 x 和 y 差异,然后计算角度。
假设x1,y1是字符坐标,x2,y2是目标坐标:
(x2-x1)将给出 x 差值,(y2-y1)将给出 y 差异,ArcTangent ( (y2-y1) / (x2-x1))会给你以弧度为单位的角度。angleInRadians * (180/pi)会给你以度为单位的角度。4*ArcTangent(1)会给你pi现在在 JavaScript 中:
var angle = Math.round(Math.atan((y2 - y1) / (x2 - x1)) * (180 / (4 * Math.atan(1))));
Run Code Online (Sandbox Code Playgroud)
或者按照莫里斯的建议,使用Math.atan2:
var angle = Math.round(Math.atan2(y2 - y1 , x2 - x1) * (180 / (4 * Math.atan(1))));
Run Code Online (Sandbox Code Playgroud)这是一个例子:
var angle = Math.round(Math.atan((y2 - y1) / (x2 - x1)) * (180 / (4 * Math.atan(1))));
Run Code Online (Sandbox Code Playgroud)
var angle = Math.round(Math.atan2(y2 - y1 , x2 - x1) * (180 / (4 * Math.atan(1))));
Run Code Online (Sandbox Code Playgroud)
$(function () {
$(document).on("mousemove", function (ev) {
var x1 = 200,
y1 = 200;
var x2 = ev.clientX,
y2 = ev.clientY;
var d = Math.sqrt(Math.pow((y2 - y1),2)+Math.pow((x2 - x1),2));
var angle = Math.round(Math.atan2((y2 - y1) , (x2 - x1)) * (180 / (4 * Math.atan(1))));
console.log(angle);
$("#line").css({
"transform":"rotate("+angle+"deg)",
"width":d+"px"
});
});
});Run Code Online (Sandbox Code Playgroud)
这是Fiddle如果您使用移动设备的话。
| 归档时间: |
|
| 查看次数: |
1588 次 |
| 最近记录: |