标题,我想让你的程序在按下按钮一次后拍摄一个球,然后它继续前进,直到它完成你就无法做任何事情。以下解雇的当前代码。
public void act()
{
// Steps for calculating the launch speed and angle
ProjectileWorld myWorld = (ProjectileWorld) getWorld();
double shotStrength = myWorld.getSpeedValue();
double shotAngle = myWorld.getAngleValue();
// Checks to see if the space key is pressed, if it is, the projectile is fired
String key = Greenfoot.getKey();
if ("space".equals(key))
{
//xSpeed and ySpeed changed as requirements say
xSpeed = (int)(shotStrength*Math.cos(shotAngle));
ySpeed = -(int)(shotStrength*Math.sin(shotAngle));
actualX += xSpeed;
actualY += ySpeed;
setLocation ((int) actualX, (int) actualY);
}
现在,这使得当我拿着空格键时球只会移动,因为就是这样,我可以放开空格键并在球还在空中时改变shotStrength和shotAngle
答案 0 :(得分:0)
这里的关键是将“行为”方法的上下文状态更改为“移动球”。
有很多方法可以实现这一点,但基本上取决于如何调用act()。
我的第一个想法是做这样的事情:
public enum ActionMode{ MovingBall, Shooting, Waiting, Etc }
public void act()
{
// Steps for calculating the launch speed and angle
ProjectileWorld myWorld = (ProjectileWorld) getWorld();
double shotStrength = myWorld.getSpeedValue();
double shotAngle = myWorld.getAngleValue();
// Checks to see if the space key is pressed, if it is, the projectile is fired
String key = Greenfoot.getKey();
if ("space".equals(key)){
mode = ActionMode.MovingBall;
}
while(mode==ActionMode.MovingBall){
//xSpeed and ySpeed changed as requirements say
xSpeed = (int)(shotStrength*Math.cos(shotAngle));
ySpeed = -(int)(shotStrength*Math.sin(shotAngle));
actualX += xSpeed;
actualY += ySpeed;
setLocation ((int) actualX, (int) actualY);
if( ballHasFinishedMoving(actualX, actualY) ){
mode==ActionMode.Waiting;
}
}
...
}
private boolean ballHasFinishedMoving( int actualX, int actualY ){
logic to determine if ball has finished.
}