简体   繁体   English

在Point2D中使用距离将变量与数组进行比较

[英]Using distance in Point2D to compare variable to array

My goal is to return true if a Door is near by (a Door is a subclass of Game Object and the allObjectsInWorld is an ArrayList which contains all the game objects in the world including this door) I return false when i am close to the door. 我的目标是如果门在附近(门是游戏对象的子类,而allObjectsInWorld是包含世界上所有游戏对象(包括此门)的ArrayList),则返回true。当我靠近门时,返回false 。 get is door returns true if the object is a door 如果对象是门,则get is door返回true

GameObject.position is a Point2D point GameObject.position是Point2D点

public boolean isDoorNear(GameObject user) {
    boolean tempBoo = false;
    for(int i = 0; i < allObjectsInWorld.size();i++) {
        GameObject a = (GameObject) allObjectsInWorld.get(i);  //checks to see if something is there
        if( user.position.distance(a.position) <= 2.0 && a.isDoor) {
            tempBoo = true;
        }
        else {
            tempBoo = false;
        }
    }
    return tempBoo; 
}

The line tempBoo = false is bad: it changes the return value to true even if some door was detected before. tempBoo = false是错误的:即使之前检测到某个门,它也会将返回值更改为true Simply rely on the initialization to provide the default return of false unless there was any door nearby. 只需依靠初始化即可提供默认的false返回,除非附近没有任何门。

But you can avoid all that tempBoo stuff completely by returning early: 但是您可以通过尽早返回来完全避免所有tempBoo东西:

public boolean isDoorNear(GameObject user) {
    for(int i = 0; i < allObjectsInWorld.size();i++) {
        GameObject a = (GameObject) allObjectsInWorld.get(i);
        if( user.position.distance(a.position) <= 2.0 && a.isDoor)
            return true;
    }
    return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM