简体   繁体   English

Java 2D引力?

[英]Java 2D gravity?

I am making a 2D Java game and i'm trying to figure out how to add basic "gravity" 我正在制作一个2D Java游戏,我正在试图弄清楚如何添加基本的“引力”

my current code is this: 我目前的代码是这样的:

    public void checkCollision() {
    Rectangle player_rectangle = new Rectangle(player.getX(),player.getY(),32,32);

    for(Wall wall : walls) {

        Rectangle wall_rectangle = new Rectangle(wall.getX(), wall.getY(), 32,32);

        if(player_rectangle.intersects(wall_rectangle)) {

            player.yspeed = 0;

        } else {
            player.yspeed = 1;
        }
    }

For some reason my code just goes straight through the walls even if it is touching it. 出于某种原因,即使触摸它,我的代码也直接穿过墙壁。 I want it to hit the wall if one is present beneath it and if there isnt then keep falling. 如果有一个人在它下面,如果没有,那么我希望它能够撞到墙上然后继续下降。

you're iterating over all your walls. 你在所有的墙上迭代。 If the wall intersected is not the last wall in the list, subsequent walls may reset your speed to 1. Break your loop when you detect intersection. 如果相交的墙不是列表中的最后一个墙,则后续墙可能会将您的速度重置为1.当您检测到交叉点时断开循环。 Specifically: 特别:

if(player_rectangle.intersects(wall_rectangle)) {
    player.yspeed = 0;
    break;

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

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