Код: Выделить всё
public class Player extends GameObject {
private float width=32 , height=64;
private float gravity = 0.1f; //il suffisso f serve per indicare che è float
private final float MAX_SPEED=10;
private Handler handler;
public Player(float x, float y, Handler handler, ObjectId id){
super(x, y, id);
this.handler=handler;
}
public void tick(ArrayList object) {
//Aggiorna la posizione del giocatore in base alla sua velocità.
x+=velX;
y+=velY;
if(gravityInverted){
velY+= -gravity; //inverti gravità --> sale
}else
velY+=gravity; //gravità normale --> scende
if(velY> MAX_SPEED){
velY=MAX_SPEED; //limito la velocità
} else if (velY < -MAX_SPEED) {
velY = -MAX_SPEED;
}
x+=3;
Collision(object);
}
private void Collision(ArrayList objects){
for(int i=0; i< handler.object.size(); i++){
GameObject tempObject= handler.object.get(i);
if(tempObject.getId() == ObjectId.Block){
if (getBoundsTop().intersects(tempObject.getBoundsBot())) {
y=tempObject.getY() +32;
velY = 0;
canSwitchGravity=true;
}
if (getBoundsBot().intersects(tempObject.getBoundsTop())) { //intersects verifica se 2 rettangoli si intersecano
y=tempObject.getY() - height;
velY = 0;
canSwitchGravity=true;
}
//Right
if (getBounds().intersects(tempObject.getBounds())) {
x=tempObject.getX() -32;
}
//left
if (getBoundsLeft().intersects(tempObject.getBounds())) {
x=tempObject.getX() +32;
}
}
}
}
public void render(Graphics g) {
g.setColor(Color.blue);
g.fillRect((int)x, (int) y,(int)width, (int)height);
}
//definisco i rettangoli di collisione in diverse direzioni (alto, basso, sinistra e destra) per il giocatore
public Rectangle getBoundsBot() {
return new Rectangle((int)(x+(width/2)-(width/2)/2), (int) (y+(height/2)) ,(int)width/2, (int)height/2 );
}
public Rectangle getBoundsTop() {
return new Rectangle((int)(x+(width/2)-(width/2)/2), (int) y,(int)width/2, (int)height/2 );
}
public Rectangle getBounds() {//right
return new Rectangle((int)(x+width-5), (int) y+5,(int) 5, (int)height-10 );
}
public Rectangle getBoundsLeft() {
return new Rectangle((int)x, (int) y+5,(int) 5, (int)height-10 );
}
}
Код: Выделить всё
public class Game extends Canvas implements Runnable{
private boolean running = false;
private Thread thread;
public static int HEIGHT,WIDTH;
private Menu menu;
public State gameState = State.Menu;
public int score = 0;
Handler handler;
Camera cam;
Random rand = new Random();
public synchronized void start(){
if(running) //se è true il metodo ritorna immediatamente e non fa nulla (il gioco è già in esecuzione).
return;
running=true;
thread = new Thread(this); // crea un nuovo thread che eseguirà il codice del metodo run() della tua classe Game(this si riferisce a game poichè thread accetta oggetto runnable e game implemetna runnable).
thread.start(); //chiama il metodo run
}
private void init(){
WIDTH= getWidth();
HEIGHT = getHeight();
handler = new Handler();
cam = new Camera(0,0);
menu = new Menu(this, handler, cam);
this.addKeyListener(new KeyInput(handler));
this.addMouseListener(menu);
}
public void run(){ //aggiungo ciclo di gioco
init();
this.requestFocus(); // Garantisce che la finestra di gioco riceva il focus per permettere l'interazione dell'utente tramite tastiera e mouse con la finestra di gioco.
long lastTime = System.nanoTime();
double amountOfTicks = 60.0; //il gioco aggiorna la sua logica 60 volte al secondo
double ns = 1000000000/amountOfTicks; // è il numero di nanosecondi che devono passare tra un tick e l'altro per ottenere esattamente amountOfTicks tick al secondo
double delta = 0; //delta è essenziale per mantenere il gioco aggiornato a un ritmo costante di 60 volte al secondo
long timer = System.currentTimeMillis();
int updates = 0;
int frames = 0;
while (running) {
long now = System.nanoTime();
delta += ( now - lastTime)/ ns; // tiene traccia del tempo trascorso tra due esecuzioni del ciclo, per assicurarsi che gli aggiornamenti logici (tick) avvengano esattamente a 60
lastTime = now ; //now - lastTime calcola quanto tempo è passato dall'ultima iterazione del ciclo
while (delta >=1) { //Questo valore viene diviso per ns (cioè il tempo tra un tick e l'altro), per ottenere un valore che rappresenta quante frazioni di tick sono trascorse
tick();
updates++;
delta--;
}
render();
frames++;
if(System.currentTimeMillis() - timer > 1000){
timer+=1000;
System.out.println("FPS: " + frames + " TICKS: " + updates);
frames=0;
updates=0;
}
}
}
//metodo che è responsabile dell'aggiornamento della logica del gioco (es. movimento dei personaggi, calcolo delle collisioni, ecc.)
private void tick(){
handler.tick();
if (gameState == State.Game) {
cam.tick();
score ++;
for (int i = 0; i < handler.object.size(); i++) {
GameObject tempObject = handler.object.get(i);
if (tempObject.getId() == ObjectId.Player) {
Player player = (Player) tempObject; // Ottieni l'istanza del player
// Controlla se il player è fuori dallo schermo
if (player.getY() > (cam.getY() + Game.HEIGHT+64) || player.getY() < cam.getY()-64 || player.getX() < (-1 *cam.getX()-32) ) {
gameState = State.End;
}
}
}
} else if (gameState == State.Menu || gameState == State.End) {
menu.tick();
}
}
//metodo per disegnare sullo schermo usando una strategia di buffering per migliorare la fluidità e ridurre lo sfarfallio.
private void render(){
BufferStrategy bs = this.getBufferStrategy();//Recupera la strategia di buffering corrente
if(bs== null){ //Se non esiste una strategia di buffering, ne crea una
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
Graphics2D g2d=(Graphics2D) g;//trasformo g in g2d perchè graphics2d fornisce funzioni + avanzate come la traslazione
////////////////////////////
//Draw here
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
if (gameState == State.Game) {
g2d.translate(cam.getX(), cam.getY());//begin of cam
//translate() sposta l'intera area di disegno in base alle coordinate della telecamera.
handler.render(g);
g.drawString("Score: "+ score, (int)(-cam.getX()+64),(int) (-cam.getY()+32));
g2d.translate(-cam.getX(), -cam.getY());//end of cam
//Se non usassi g2d.translate(-cam.getX(), -cam.getY()), la traslazione si accumulerebbe ad ogni ciclo di rendering, ciò che disegnerei nei cicli successivi sarebbe ulteriormente spostato di una certa quantità rispetto alla posizione corrente
}else if (gameState == State.Menu || gameState == State.Help || gameState == State.End) {
menu.render(g);
}
g.dispose();
bs.show();
}
public void LoadImageLevel( BufferedImage image){
int w = image.getWidth();
int h = image.getHeight();
System.out.println("width, height: " + w + " "+ h);
for(int xx =0; xx
Подробнее здесь: [url]https://stackoverflow.com/questions/79018170/the-player-changes-gravity-even-when-he-should-not[/url]