我正在为塔防游戏制作原型。现在,我正在攻击一些箭头(就像后来的塔楼中的子弹一样),它应该指向怪物的中心。我设法在第一次逻辑调用中相应地设置旋转,但我不知道如何更改代码以防止发生以下情况:http://recordit.co/jBdXtGGeN8
简而言之:箭头一直旋转,即使它会产生旋转,然后只旋转小值以适应移动的怪物。
箭头的构造函数:
public Shot(Vector2 position, EntityV2 target) {
this.sprite = SpriteStore.get().getSprite("resources/sprites/arrowShot.png");
this.position = position;
this.targetEntity = target;
this.rotation = Math.atan2(targetEntity.getBounds().getCenterY()
- position.getY(), targetEntity.getBounds()
.getCenterX() - position.getX());
this.rotation += Math.PI / 2.0;
this.angle = Math.toDegrees(rotation);
this.movementVector = new Vector2();
bounds = new Rectangle((int) position.getX(), (int) position.getY(), sprite.getWidth(), sprite.getHeight());
}
逻辑更新通话:
public void move(float delta) {
position.add((movementVector.getX() * delta) / 1000, (movementVector.getY() * delta) / 1000);
if(targetEntity.getBounds().contains(position.getX(), position.getY())) {
isDone = true;
}
bounds.setLocation((int) position.getX(), (int) position.getY());
rotation = Math.atan2(targetEntity.getBounds().getCenterY()
- position.getY(), targetEntity.getBounds()
.getCenterX() - position.getX());
rotation += Math.PI / 2.0;
angle = Math.toDegrees(rotation);
calculateMovementVector(targetEntity.getCenter());
}
渲染电话:
public void draw(Graphics2D g) {
int x = (int) position.getX() + sprite.getWidth()/2;
int y = (int) position.getY() + sprite.getHeight()/2;
g.rotate(angle, x, y);
sprite.draw(g, (int) position.getX(), (int) position.getY());
g.rotate(-angle, x, y);
}
我计算运动Vector的方式(应用到位置):
private void calculateMovementVector(Vector2 to) {
float dX = to.getX() - (float) bounds.getCenterX();
float dY = to.getY() - (float) bounds.getCenterY();
float distance = (float) Math.sqrt(dX * dX + dY * dY);
float sX = speed * dX / distance;
float sY = speed * dY / distance;
movementVector.set(sX, sY);
}
答案 0 :(得分:0)
我假设您的Graphics2D
对象是java.awt.Graphics2D
的实例。那就是说,我想我知道你的问题:
当the documentation for rotate()
指定您应该传递弧度值时,您正在使用度数。由于度数的度量与弧度的量度差别很大,因此您会发现度数的微小变化会导致弧度变化非常大(可能超过整圆)。尝试评论度转换,并使用rotation
代替angle
来调用g.rotate()