如何在JavaScript中计算弹丸的弧度?

时间:2018-11-14 18:52:43

标签: javascript html css jquery-animate

我正在创建一个用于课业的游戏,将两个坦克放在画布上,并在其中输入用于输入炮塔的初始速度和角度的框,然后再按下一个按钮来发射弹丸(目前是圆形的div元素),在这种情况下调用函数为fire1。我已经忙了几天,似乎无法正常工作,“ bullet”是我的div元素。

function fire1 () {
    var canvas = document.getElementById("canvas")
    var bullet = document.getElementById("bullet");
    bullet.style.visibility = "visible"

    var start = null;
    var intialVelocity = velocity1.value
    var angle = angle1.value
    var g = 9.81;
    var progress, x, y;

function step(timestamp) {
    if(start === null) start = timestamp;
    progress = (timestamp - start)/1000;

    x = (turret1.x + 80) + (intialVelocity*progress)
    y = (turret1.y - 400) + (intialVelocity*progress)*Math.sin(angle*toRadians) - (0.5*g*(progress^2));//)

    bullet.style.left = x + "px";
    bullet.style.bottom = y + "px";

    requestAnimationFrame(step);
  }
  requestAnimationFrame(step);
}

下面是我的CSS子弹。

#bullet {
position: absolute;
left: 0;
bottom: 50%;
width: 1em;
height: 1em;
border-radius: 0.5em;
background: red; 
visibility: hidden;
}

我对javascript,css和html非常陌生,因此非常乐于助人,我正在尝试合并trajectory formula这项功能吗?我还希望它具有动画效果,以便在发射时遵循一条路径。谢谢

1 个答案:

答案 0 :(得分:1)

我很久以前就解决了这个问题,但忘记更新解决方案,下面是如何计算轨迹的 x 和 y:

x = ((turret.anchorX + negative*(initialVelocity*progress*Math.cos(angle*toRadians)))); //x-coordinate for bullet calculated by using x=ut.

y = ((720 - turret.anchorY + (initialVelocity*progress*Math.sin(angle*toRadians)) + (0.5*g*(Math.pow(progress,2))))); //y-coordinate for bullet calculated by usnig ut+0.5at^2.