开发者

Homing Missile Behavior in Java

开发者 https://www.devze.com 2023-02-13 07:55 出处:网络
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 s

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){
开发者_如何学JAVA    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;
    }
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号