首页 > 解决方案 > 如何在javascript中计算弹丸的弧度?

问题描述

我正在为课程作业创建一个游戏,两个坦克放置在画布上,输入框用于输入炮塔的初始速度和角度,然后是一个用于发射射弹的按钮(当前是圆形的 div 元素),它调用在这种情况下,函数是 fire1。我已经搞砸了几天,似乎无法让它工作,“子弹”是我的 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 非常陌生,因此非常需要帮助,我正在尝试合并轨迹公式这行得通吗?我还希望它具有动画效果,以便在触发时遵循一条路径。谢谢

标签: javascripthtmlcssjquery-animate

解决方案


我很久以前解决了这个问题,但忘记更新解决方案,下面是如何计算轨迹的 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.

推荐阅读