[英]Java objects escaping window frame
So I made a game and I want the enemies to bounce off the wall when they hit in a random x and y speed.所以我做了一个游戏,我希望敌人以随机的 x 和 y 速度击中时从墙上反弹。 However, somehow these little buggers are still getting out of the window.
然而,不知怎的,这些小家伙们仍然逃出了窗外。 Most the time it works but every like 10ish times it will sneak out the border and I can't figure out how.
大多数情况下它都有效,但每隔 10 次它就会偷偷溜出边界,我不知道怎么做。
@Override
public void tick()
{
x += speedX;
y += speedY;
Random r = new Random();
//BUGS
if(y <= 0 || y >= Game.HEIGHT - 48) //This is correct size of the window edges
{
if(speedY <= 0)
speedY = (r.nextInt(8) + 1);
else
speedY = -(r.nextInt(8) + 1);
}
if(x <= 0 || x >= Game.WIDTH - 32) //This is correct size of the window edges
{
if(speedX <= 0)
speedX = (r.nextInt(8) + 1);
else
speedX = -(r.nextInt(8) + 1);
}
Issues:问题:
y >= Game.HEIGHT - 48
, do y >= Game.HEIGHT - WINDOW_EDGES
(or something similar)y >= Game.HEIGHT - 48
,做y >= Game.HEIGHT - WINDOW_EDGES
(或类似的东西)y <= 0
or y >= Game.HEIGHT -SOME_CONSTANT
separately, and gear the results based on this finding to avoid getting caught in a speed "trap".y <= 0
或y >= Game.HEIGHT -SOME_CONSTANT
,并根据此发现调整结果以避免陷入速度“陷阱”。 This is your main problem in fact. eg,例如,
if (y <= 0) {
speedY = r.nextInt(8) + 1; // change 8 to a constant
} else if (y >= Game.HEIGHT - SOME_CONSTANT) {
speedY = -(r.nextInt(8) + 1);
}
Same for x and speedX x 和 speedX 相同
Regarding:关于:
2) I would like to do that but since I have multiple object sizes, I have to change the edges.
2)我想这样做,但由于我有多个对象大小,我必须改变边缘。
Then each object should have a method that returns its edge size (or whatever property is needed), and you should use this, again, not magic numbers然后每个对象都应该有一个方法来返回它的边缘大小(或任何需要的属性),你应该再次使用这个,而不是幻数
3) I tried swapping and they just shot off the screen.
3)我尝试交换,他们只是从屏幕上开枪。
I don't know what you mean by this or what specific code changes you may have made.我不知道您的意思是什么,或者您可能进行了哪些特定的代码更改。
If still stuck, consider creating and posting a valid Minimal Reproducible Example如果仍然卡住,请考虑创建并发布有效的最小可重现示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.