gpt4 book ai didi

javascript - 球物理从程度表现不正常

转载 作者:行者123 更新时间:2023-12-03 04:06:49 26 4
gpt4 key购买 nike

我正在尝试构建一个游戏,其中您有一个大炮图像,该图像将不断指向您的鼠标,并且单击时会向大炮的方向发射一个球。我明白球运动的数学应该是这样的:vx= -vi * cos(θ) vy= vi * sin(θ)。我让图像指向鼠标,但是当它发射球时,(在我看来)它似乎朝随机方向移动。代码片段:

var ball = {
x: 20,
y: 20,
vx: 0,
vy: 0
}
setInterval(move_ball, 100);
var degree;

function rotate(e, elt) {
var offset = elt.offset();
var center_x = (offset.left) + (elt.width() / 2);
var center_y = (offset.top) + (elt.height() / 2);
var mouse_x = e.pageX;
var mouse_y = e.pageY;
var radians = Math.atan2(mouse_x - center_x, mouse_y - center_y);
degree = (radians * (180 / Math.PI) * -1);
if (degree < 90 && degree > 0) {
degree = 90
}
if (degree > -180 && degree < 0) {
degree = 179
}
$(elt).css('-moz-transform', 'rotate(' + degree + 'deg)');
$(elt).css('-webkit-transform', 'rotate(' + degree + 'deg)');
$(elt).css('-o-transform', 'rotate(' + degree + 'deg)');
$(elt).css('-ms-transform', 'rotate(' + degree + 'deg)');
document.getElementById('out').innerHTML = degree;
}


document.onmousemove = function(e) {
rotate(e, $('#img'));
}
document.onclick = function() {
document.getElementById('ball').style.right = '20px';
document.getElementById('ball').style.bottom = '20px';
ball.vx = 5 * Math.cos(degree);
ball.vy = 5 * Math.sin(degree);
}

function move_ball() {
ball.x = parseInt(document.getElementById('ball').style.right.substring(0, document.getElementById('ball').style.right.length - 3));
ball.y = parseInt(document.getElementById('ball').style.bottom.substring(0, document.getElementById('ball').style.bottom.length - 3));
ball.x += Math.abs(ball.vx);
ball.y += Math.abs(ball.vy * -1);
document.getElementById('ball').style.right = ball.x.toString() + 'px';
document.getElementById('ball').style.bottom = ball.y.toString() + 'px';
}
/*
vx= -vi*cos(θ)
vy= vi*sin(θ)
θ= sprite direction
*/
#img {
width: 20px;
height: 40px;
position: absolute;
bottom: 15px;
right: 15px;
}

#ball {
width: 10px;
height: 10px;
position: absolute;
bottom: 20px;
right: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="img" src="https://lh3.googleusercontent.com/FF_QMZJ187zosdjWPzrnzJKlHl8UvtPjIJr3Uma7LEgPCz22_KN5wqJ_Auka3z3-x3YvCw=s85" />
<img id="ball" src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/Circle_-_black_simple_fullpage.svg/1000px-Circle_-_black_simple_fullpage.svg.png">
<div id="out"></div>

最佳答案

您忘记将 Angular 转换回弧度 Angular 。 Math.cos(level); Math.sin(level); 确实会返回看似随机的结果。

<小时/>

当然,你必须反转整个计算

 degree = -180/pi*atan2(x,y)

  var radians = -degree*Math.PI/180;
ball.vx = 5 * Math.sin(radians);
ball.vy = 5 * Math.cos(radians);

请注意,获取笛卡尔点 (x,y) Angular 调用约定是 atan2(y,x),而您使用 atan2(x,y) code>,强制在速度计算中交换 sin 和 cos。

关于javascript - 球物理从程度表现不正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44513601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com