游戏物理Java:移动,需要放慢速度
好的,我已经用java做了几周的实验,在课堂和在线教程之后。我做了一个简单的游戏,方块落在屏幕底部,而玩家控制一个小球,只在x轴上移动并试图避开它们
我遇到的问题是,方块开始下降得太快。现在我把它们设置如下:
ix = 0;
iy = 1;
然后在我的move()方法中,我有以下内容:
hitbox.x += ix;
hitbox.y += iy;
在本例中,ix和iy都是整数
我的第一个假设是将int更改为float,然后使用:
ix= 0;
iy = 0.5;
然后:
hitbox.x += ix;
hitbox.y += 0.5f;
但这只是冻结了物体的轨迹。我认为这是因为跳线被视为整数,所以我想如果我修改我的getX()和getY()方法,也许我可以通过某种方式操纵它们来使用十进制数?但我不太确定该怎么做。对此问题的任何帮助/提示/解决方案都将不胜感激
这里有一些相关的代码,如果还需要,请告诉我
敌方经理:
public class EnemyManager {
private int amount;
private List<Enemy> enemies = new ArrayList<Enemy>();
private GameInJavaOne instance;
public EnemyManager(GameInJavaOne instance, int a){
this.amount = a;
this.instance = instance;
spawn();
}
private void spawn(){
Random random = new Random();
int ss = enemies.size();
// If the current amount of enemies is less than the desired amount, we spawn more enemies.
if(ss < amount){
for(int i = 0; i < amount - ss; i++){
enemies.add(new Enemy(instance, random.nextInt(778), random.nextInt(100)+1));
}
// If its greater than the desired number of enemies, remove them.
}else if (ss > 20){
for(int i = 0; i < ss - amount; i++){
enemies.remove(i);
}
}
}
public void draw(Graphics g){
update();
for(Enemy e : enemies) e.draw(g);
}
private void update() {
boolean re = false;
for(int i = 0; i < enemies.size(); i ++){
if(enemies.get(i).isDead()){
enemies.remove(i);
re = true;
}
}
if(re) spawn();
}
public boolean isColliding(Rectangle hitbox){
boolean c =false;
for(int i = 0; i < enemies.size(); i ++){
if(hitbox.intersects(enemies.get(i).getHitbox())) c = true;
}
return c;
}
}
实体:
public abstract class Entity {
protected int x, y, w, h;
protected boolean removed = false;
public Entity(int x, int y){
this.x = x;
this.y = y;
}
public void Draw(Graphics g){
}
public int getX() { return x; }
public int getY() { return y; }
public int getH() { return h; }
public int getW() { return w; }
}
敌人阶级:
public class Enemy extends Entity{
private Rectangle hitbox;
private int ix, iy;
private boolean dead = false;
private GameInJavaOne instance;
public Enemy(GameInJavaOne instance, int x, int y){
super(x, y);
this.instance = instance;
hitbox = new Rectangle(x, y, 32, 32);
ix = 0;
iy = 1;
}
private void move(){
if(instance.getStage().isCollided(hitbox)){
iy =0;
dead = true;
}
hitbox.x += ix;
hitbox.y += iy;
}
public boolean isDead() {return dead;}
public Rectangle getHitbox() {return hitbox; }
public void draw(Graphics g){
move();
g.setColor(Color.MAGENTA);
g.fillRect(hitbox.x, hitbox.y, hitbox.height, hitbox.width);
}
}
# 1 楼答案
您正在使用
Rectangle
类来表示方框的位置(即使您将其称为hitbox),Rectangle
确实有成员x
和y
,它们是整数,因此当您调用你真正要说的是
rectangle.x+=(int)0.5f;
和(int)0.5f==0
如果需要浮点精度,
Rectangle
类根本不适合保持长方体的位置。考虑将框的实际位置保持为双或浮动,并将其转换为int来渲染它。所以你的渲染代码会变成
其中
positionX
和positionY
是双倍的。(如果希望将x
和y
放在一起,也可以使用Vector2d
)其他要点
x
、y
、w
和h
扩展Entity
类,但从未使用它们,这似乎很危险,为什么要扩展Entity
,但要重新创建自己的位置代码李>