我正在制造小行星,我试图制造子弹机。子弹应该朝着船的方向(一个角度)走,但是我不知道如何使子弹朝那个角度方向走。而是向上,向下或向右/向左移动。我尝试过的代码无法正常工作:
class Bullet
{
float x,y,vx,vy;
Bullet()
{
rectMode(CENTER);
x = 0;
y = 0;
vx = 100 * cos(ang);
vy = 100 * sin(ang);
}
void draw2()
{
vx = 100 * cos(ang);
vy = 100 * sin(ang);
x += vx;
y += vy;
pushMatrix();
translate(width/2,height/2);
translate(5,0);
rotate(ang);
rect(x,y,10,10);
popMatrix();
}
}
其余代码:
float ang = 0;
boolean spara = false;
Bullet b;
void setup()
{
size(800,600);
rectMode(CENTER);
frameRate(60);
asteroidi = new Asteroide[10];
b = new Bullet();
}
void update()
{
}
void draw()
{
update();
background(200,200,200);
fill(255);
pushMatrix();
translate(width/2,height/2);
translate(25,0);
rotate(ang);
rect(0,0,50,50);
popMatrix();
if(spara)
b.draw2();
}
void keyPressed()
{
switch (keyCode)
{
case RIGHT:
ang += 0.1;
break;
case LEFT:
ang -= 0.1;
break;
case 32:
if (spara) spara = false;
if (!spara); spara = true;
break;
}
}
[draw2()
为boolean spara
时,我称为true
功能。
您必须执行以下操作:
以这种方式绘制项目符号矩形,它的中心在(0,0):rect(0, 0, 10, 10);
在移动方向上旋转矩形:rotate(ang);
将矩形转换为新位置:translate(x, y);
由于translate
和translate
之类的操作定义了一个新矩阵并将当前矩阵乘以新矩阵,所以矩阵操作必须按相反的顺序进行。
请注意,与rotate
和rotate
的角度必须以弧度而非角度设置。顺便问一下,您确定100的速度不远吗?
sin()
管理sin()
中的项目符号并在按下SPACE时产生(添加)新项目符号:
cos()
更新(更新)阵列中的所有项目符号。仅保留仍在窗口中的子弹。将窗口中的项目符号存储到新数组中,并用新数组替换项目符号数组:
cos()
[在class Bullet
{
float x, y, v, ang;
Bullet(float x, float y, float v, float ang)
{
this.x = x;
this.y = y;
this.v = v;
this.ang = ang;
}
void update() {
x += v * cos(ang);
y += v * sin(ang);
}
void draw()
{
pushMatrix();
// transalte rectangle to new position
translate(x, y);
// rotate rectangle in direction of move
rotate(ang);
// draw rectangle around center
rect(0, 0, 10, 10);
popMatrix();
}
}
中循环绘制项目符号:
ArrayList
ArrayList