java - 使用 PVectors 使速度恒定

标签 java processing game-physics

我正在处理一个学校项目,但遇到了一些问题。我有一个 bulletList 数组,它在我的 draw() 类中循环,其中包含按下空格键时初始化的 Bullet 对象。

if(key==' '){
float currentPlayerX=playerX;
float currentPlayerY=playerY;
float currentMouseX=mouseX;
float currentMouseY=mouseY;
bullets.add(new 
Bullet(currentPlayerX,currentPlayerY,currentMouseX,currentMouseY));
}

//in the draw method()
for(Bullet b: bullets){
b.shoot();
}

class Bullet{
float bulletX;
float bulletY;
float rise;
float run;

Bullet(float pX, float pY,float mX,float mY){ 

//I get the slope from the mouse position when the bullet was instantiated 
to the bullet position (which starts at the player position and is
incremented out by the slope as shoot() is called

rise=(mY-pY)/12;
run=(mX-pX)/12;
bulletX=pX;
bulletY=pY;
}

void shoot(){

fill(255,0,0);
rect(bulletX,bulletY,7,7);
bulletX+=run;
bulletY+=rise;
}
}

本质上,Bullet的轨迹是在第一次创建bullet对象时确定的,最终目标是:将鼠标移动到所需的方向,按空格键酒吧,看着子弹飞去。问题是速度永远不是恒定的。当鼠标远离Player对象时,速度还好,但是随着鼠标靠近,riserun变得越来越小,Bullet 速度变得非常小。实际上,我最终搞乱了 riserun float ,并将它们除以 12,因为在其初始值时,Bullet 不是可见的。

我听说 PVectors 是提高游戏速度的好方法,但我们从未在类里面介绍过它们,而且我真的不知道从哪里开始。我也尝试过除以和乘以一个常数来尝试获得恒定的速度,但我基本上是在黑暗中拍摄的。非常感谢任何帮助,如果您对我的代码如何工作有任何疑问,请询问;我很高兴澄清。

最佳答案

您正在寻找的是一些基本的三角学知识。基本上我会 break your problem down into smaller steps :

第一步:获取子弹源和鼠标之间的角度。 Google“获取两点之间的角度”以获取大量资源。

第二步:将角度转换为单位 vector ,它是一个 x/y 对,您可以将其视为标题。 Google“将角度转换为单位 vector ”以获得大量资源。

第三步:将该单位 vector 的 x 和 y 值乘以某个速度,以获得每帧子弹应移动的量。

PVector 类确实提供了其中一些功能。查看the reference获取有用功能的列表。

如果您仍然遇到困难,请将问题范围缩小到 MCVE 。这可以像跟随鼠标画一圈一样简单。祝你好运!

关于java - 使用 PVectors 使速度恒定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50585099/

相关文章:

java.lang.ClassNotFoundException : org. apache.poi.xwpf.usermodel.IRunBody

java - Apache Tika 提取扫描的 PDF 文件

用真实测量值处理图纸

python - 关键优先级的 Sprite 运动问题

java - 在屏幕右下角的位置

java - 如何在java中对硬盘驱动器的文件读/写进行排队?

Java 一个 liner for 循环

java - 使用eclipse进行处理,无法让java应用程序运行

javascript - 不同球质量的真实球碰撞 - 小球阻止大球

c++ - btDefaultMotionState 的多个实例,全部被忽略,但有一个