使用PVectors使速度保持不变

问题描述 投票:1回答:2

我正在处理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速度变得非常小。我实际上最终搞乱了riserun花车,并将它们除以12,因为在它们的初始值时,Bullet不可见。

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

java processing game-physics
2个回答
1
投票

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

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

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

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

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

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


0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.