简体   繁体   English

Java 边缘碰撞检测

[英]Collision Detection with edges Java

I am attempting to add collision detection with the edges using 4 images which represent a walking man.我正在尝试使用 4 个代表行走的人的图像添加边缘碰撞检测。 Once the image hits the wall it should reverse and move the other way until it hits the wall and reverses direction once again.一旦图像撞到墙壁,它应该反转并以另一种方式移动,直到它撞到墙壁并再次反转方向。 How would i go about this?我会怎么做呢? Here is my code so far:到目前为止,这是我的代码:

class Walker {
    int x = 0;
    int y;
    int speed;
    PImage img1, img2, img3, img4;
    int count = 0;

    Walker(int y, int speed) {
        this.y = y;
        img1 = loadImage("walk1.gif");
        img2 = loadImage("walk2.gif");
        img3 = loadImage("walk3.gif");
        img4 = loadImage("walk4.gif");
        this.speed = speed;

    }

    void render() {

        if (count < 10)
            image(img1, x, y);
        else if (count < 20)
            image(img2, x, y);
        else if (count < 30)
            image(img3, x, y);
        else if (count < 40)
            image(img4, x, y);
        else {
            count = -1;
        }
        count++;

    }

    void move() {
        x = x + speed;
    }

}


Walker walter;

void setup() {
    size(500, 500);
    walter = new Walker(150, 3);
}

void draw() {
    background(125);
    walter.render();
    walter.move();
}

You have to reverse the speed, when ever the walker hits the wall.当助行器撞到墙上时,您必须反转速度。 The width of an PImage is given by the property .width eg: PImage的宽度由属性.width给出,例如:

class Walker {

    // [...]

    void move()
    {
        x = x + speed;

        int man_width = img1.width; 
        if (x <= 0 || x >= width-man_width)
            speed = -speed;
    }
}

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

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