Java 中的寻的导弹行为

发布于 2024-10-19 02:23:12 字数 567 浏览 0 评论 0原文

也许是一个初学者问题,但感谢您的阅读。我正在开发一个 2d Java 游戏,其中有导弹使用以下代码跟踪对象的位置。我希望导弹在距目标达到一定的最小位移时停止寻的,此时它们应该垂直落下。现在,只要导弹处于最小位移范围内,寻的行为就会关闭,如果位移增加,寻的行为就会再次打开。 我希望该行为仅关闭一次,并在导弹的剩余使用寿命内保持关闭状态。我该如何实现此目的?

public void home(int targetX, int targetY, int scale){
    int dy = targetY - y;
    int dx = targetX - x;
    double speed, sep;

    sep = Math.sqrt(dx * dx + dy * dy);
    speed = scale/sep;

    if(dy > 50 || dx > 50){
        x += dx * speed;
        y += dy * speed;
    }
    else{
        x += 0;
        y += scale;
    }
}

Maybe a beginner question, but thank you for reading. I'm working on a 2d Java game in which I have missiles that track the position of an object using the following code. I'd like the missiles to stop homing when they reach a certain minimum displacement from their target, at which point they should fall straight down. Right now, the homing behavior turns off whenever the missile is within the minimum displacement, and turns on again if the displacement increases. I'd like the behavior to turn off only once, staying off for the remainder of the missile's lifespan. How can I accomplish this?

public void home(int targetX, int targetY, int scale){
    int dy = targetY - y;
    int dx = targetX - x;
    double speed, sep;

    sep = Math.sqrt(dx * dx + dy * dy);
    speed = scale/sep;

    if(dy > 50 || dx > 50){
        x += dx * speed;
        y += dy * speed;
    }
    else{
        x += 0;
        y += scale;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

庆幸我还是我 2024-10-26 02:23:12

添加成员变量,例如 boolean homing = true。然后,将您的条件更改为如下所示:

if (dy < 50 && dx < 50)
    homing = false;

if(homing){
    x += dx * speed;
    y += dy * speed;
}
else{
    x += 0;
    y += scale;
}

您基本上只需要打破导弹行为与其状态之间的相互依赖即可。

Add a member variable, such as boolean homing = true. Then, change your conditional to something like the following:

if (dy < 50 && dx < 50)
    homing = false;

if(homing){
    x += dx * speed;
    y += dy * speed;
}
else{
    x += 0;
    y += scale;
}

You basically just need to break the mutual dependence between you missile's behaviour and its state.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文