gpt4 book ai didi

java - 让子弹穿过屏幕的两侧

转载 作者:行者123 更新时间:2023-12-01 10:03:16 25 4
gpt4 key购买 nike

因此,对于编码作业,我们必须制作一款坦克游戏。我用这个创建了一个项目符号类:

package com.MyName.battletanks;

import com.badlogic.gdx.graphics.g2d.Sprite;

public class Bullet {
public Sprite b;
public float vx = 0;
public float vy = 0;

public Bullet(Sprite temp) { b = temp;}

public void move() { b.translate(vx*3,vy*3);}

}

我的变量如下:

Sprite Player1;
Sprite Player2;
ArrayList<Bullet> bullets;

单击空间后,它会使用以下命令创建项目符号:

if (Gdx.input.isKeyPressed(Input.Keys.SPACE)) {
Bullet bullet = new Bullet(new Sprite(new Texture("Bullet1.png")));
bullet.b.setPosition(Player1.getX() + Player1.getWidth() / 2, Player1.getY() + Player1.getHeight() / 2);
float rotation = (float) Math.toRadians(Player1.getRotation());
bullet.vx = (float) Math.cos(rotation);
bullet.vy = (float) Math.sin(rotation);
bullets.add(bullet);
}

现在,这是我的代码,用于让我的坦克从屏幕的一侧穿过到另一侧:

if (Player1.getX() > Gdx.graphics.getWidth()){
Player1.setX(-64f);
} else if(Player1.getX()<-64f){
Player1.setX(Gdx.graphics.getWidth());
}
if (Player1.getY() > Gdx.graphics.getHeight()){
Player1.setY(-64);
} else if(Player1.getY() < -64f){
Player1.setY(Gdx.graphics.getHeight());
}

现在,玩家 1 是一个 Sprite ,但是,子弹是使用数组列表和自制的子弹类创建的。因此,我无法使用为子弹所做的 Player1 代码。所以,我的问题是,如何让子弹传到屏幕的另一边?

最佳答案

您可以使用模 % 运算符执行以下操作:

bullet.position.x %= Gdx.graphics.getWidth();
bullet.position.y %= Gdx.graphics.getHeight();

这尚未经过测试,但应该可以工作。另外,我注意到您使用 2 个 float 作为速度,并且您确实应该使用 Vector2 因为这样您就可以轻松缩放和标准化它,这对于速度很有用。

关于java - 让子弹穿过屏幕的两侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36651259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com