gpt4 book ai didi

java - 保存不断变化的变量的实例

转载 作者:行者123 更新时间:2023-11-30 11:13:28 25 4
gpt4 key购买 nike

我有一个名为 angleOfGun 的浮点变量,它包含屏幕上不断移动的枪的角度。我想在单独的浮点变量 currentAngle 中保存用户单击屏幕时枪的角度。问题是,currentAngle 不断更新 angleOfGun 因为 angleOfGun 正在改变..

关于如何在设置初始值后 currentAngle 不再更新的情况下将 angleOfGun 的实例保存到 currentAngle 中,您有什么想法吗?谢谢!

    float angleOfGun = 1;

//boolean for direction of rotation
boolean clockwise = false;

/**
* Action to perform on clock tick
*
* @param g the canvas object on which to draw
*/
public void tick(Canvas g) {

int height = g.getHeight();
int width = g.getWidth();

//rotate/draw the gun
g.save();
g.rotate(angleOfGun, width - 5, 5);
g.drawRect(new RectF(width - 40, 0, width, 60), bluePaint);
g.restore();

if(ballPosition != null)
{
float currentAngle = angleOfGun;
g.save();
g.rotate(currentAngle, width - 5, 5);
ballPosition.x = ballPosition.x - ballVelocity.x;
ballPosition.y = ballPosition.y - ballVelocity.y;
g.drawCircle(ballPosition.x, ballPosition.y, 10, greenPaint);
g.restore();
}

if(clockwise)
{
angleOfGun = (angleOfGun - 1) % 360;
if(angleOfGun == 0)
{
clockwise = false;
}
}
else
{
angleOfGun = (angleOfGun + 1) % 360;
if(angleOfGun == 90)
{
clockwise = true;
}
}


}


/**
* callback method, run when when surface is touched
*/
public void onTouch(MotionEvent event) {
if(ballPosition == null && shoot == false)
{
shoot = true;
ballPosition = new PointF(0,0);
ballVelocity = new PointF(0,0);
ballPosition.x = 1280;
ballPosition.y = 0;
ballVelocity.x = 0;
ballVelocity.y = -5;
}
}

最佳答案

在你的类中你有方法 tick() 代码中有一行:

float currentAngle = angleOfGun;

因此,您不断地将 angleOfGun 的值赋给 currentAngle。因此,在您的代码中进行此声明后,您只需使用 currentAngle 代替代码中的 angleOfGun(反之亦然),这对任何事情都没有影响,因为 它们都存储相同的值
不要忘记 Java 是 OOP 语言,因此您可以利用它。我的方法是创建名为 Angle 的类,其中我可以拥有 private static float currentAngle 字段和 private float gunAngle。通过创建修改器,可以操纵此变量的值以满足任何需要。这种方法有助于简化代码,并使您可以灵活地通过添加或删除方法进行进一步更改。

关于java - 保存不断变化的变量的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26417713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com