我正在使用Java处理3和制作一个两人坦克游戏。下面是我的炮塔代码。目前,我有炮塔的目标跟随鼠标在tDir,我想能够使用上下箭头来移动目标从0到90度上下移动。
我该怎么做?谢谢。
/*
Uzair
*/
PVector mPos; //mouse position
PVector tPos; //position of turret
PVector tDir; //the firing direction of the turret
int gravMult = 3;
void setup() {
size(1200, 600);
init();
}
void init() {
//PVector initializations
mPos = new PVector(); //zero til mouse x and y exist
tPos = new PVector(width/8, height);
tDir = new PVector(); //
}
void draw() {
//clear last frame
background(100,100,140);
//check keys to see if there is new key input for turret
if (keyPressed){
if (key == 'w'){
tDir.y -= 10;
}
else if (key == 's'){
tDir.y += 10;
}
}
mPos.set(mouseX, mouseY);
tDir = PVector.sub(mPos, tPos);
tDir.normalize();
tDir.mult(50);
//draw
fill(255);
ellipse(tPos.x, tPos.y, 40, 40);
strokeWeight(5);
line(tPos.x, tPos.y, tPos.x + tDir.x, tPos.y + tDir.y);
fill(255, 0, 0);
ellipse(tPos.x + tDir.x, tPos.y + tDir.y, 10, 10);
}发布于 2017-05-23 00:00:46
从0到90度上下瞄准
这听起来像是在增加角度/旋转,而不是像当前那样增加y位置。
你需要做极坐标(角/半径)转换为笛卡尔坐标(x,y)。
这可以使用以下公式来完成:
x = cos(angle) * radius
y = sin(angle) * radius在你的情况下
tDir.x = cos(angle) * 50;
tDir.y = sin(angle) * 50;...although值得记住的是,PVector已经通过fromAngle()提供了这个功能。
下面是对代码的修改,以便使用这种思想:
PVector mPos; //mouse position
PVector tPos; //position of turret
PVector tDir; //the firing direction of the turret
int gravMult = 3;
//angle in radians
float angle = 0;
void setup() {
size(1200, 600);
init();
}
void init() {
//PVector initializations
mPos = new PVector(); //zero til mouse x and y exist
tPos = new PVector(width/8, height * .75);
tDir = new PVector(); //
}
void draw() {
//clear last frame
background(100,100,140);
//check keys to see if there is new key input for turret
if (keyPressed){
if (key == 'w'){
angle -= 0.1;
tDir = PVector.mult(PVector.fromAngle(angle),50);
}
else if (key == 's'){
angle += 0.1;
tDir = PVector.mult(PVector.fromAngle(angle),50);
}
}else if(mousePressed){
mPos.set(mouseX, mouseY);
tDir = PVector.sub(mPos, tPos);
tDir.normalize();
tDir.mult(50);
}
//draw
fill(255);
ellipse(tPos.x, tPos.y, 40, 40);
strokeWeight(5);
line(tPos.x, tPos.y, tPos.x + tDir.x, tPos.y + tDir.y);
fill(255, 0, 0);
ellipse(tPos.x + tDir.x, tPos.y + tDir.y, 10, 10);
}您可能还会发现这个答案很有用。
发布于 2017-05-22 23:13:25
堆栈溢出并不是真正为一般的“我该如何做”类型问题而设计的。这是具体的“我尝试了X,预期的Y,但得到Z”类型的问题。话虽如此,我还是会尽力在一般意义上提供帮助。
您需要将您的问题分解为较小的步骤,并一次执行这些步骤。您能否创建一个单独的独立草图,当您按下箭头键时,只会将一些东西打印到控制台上?
与该草图不同,您能否创建另一个草图,在草图顶部的变量中存储一个位置或角度?使用这些变量绘制场景,然后再一次让它自己工作。
当您让它们自己工作时,您可以考虑通过在用户按箭头键时更改草图级变量来组合它们。
如果你被困在一个具体的步骤,请张贴一个MCVE在一个新的问题,我们将从那里开始。祝好运。
https://stackoverflow.com/questions/44123286
复制相似问题