使用PVectors使速度恒定

时间:2018-05-29 13:01:06

标签: java processing game-physics

我正在处理Processing中的一个学校项目,我遇到了一些问题。我有一个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速度变为rise真的很小。实际上我最终弄乱了runBullet浮点数,并将它们除以12,因为在初始值时PVectors不可见。

我听说id是一种在游戏中获得速度的好方法,但我们从未在课堂上介绍它们,我真的不知道从哪里开始。我也尝试过划分&乘以一个常数来试图获得恒定的速度,但我基本上是在黑暗中射击。非常感谢任何帮助,如果您对我的代码如何工作有任何疑问,请询问;我很乐意澄清。

2 个答案:

答案 0 :(得分:1)

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

第一步:获取子弹源和鼠标之间的角度。对于大量资源,谷歌“在两点之间取得了一定的角度”。

第二步:将角度转换为单位向量,这是一个x / y对,您可以将其视为标题。谷歌“将角度转换为单位向量”,用于大量资源。

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

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

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

答案 1 :(得分:0)

除了Kevin的回答,我还想向您介绍一些有用的在线资源:

这些应该可以帮助您标准化,然后将矢量缩放到设定的速度,您选择是否使用PVector。