2012-10-21 2 views
1

최근에 Slick을 사용하여 Java 게임을 프로그래밍하는 방법을 배우기 시작했습니다. 저는 튜토리얼 (Youtube의 Bucky 's)을보고 Slick의 포럼에서 많이 읽었습니다. 나는 현재 완전히 갇혀있는 문제로 고심하고있다. 3 초마다 게임 루프에 새 객체를 만들려고합니다. Slick 포럼에서 저를 도우려고 노력한 사람이 있지만 아직 제대로 작동하지 않습니다. 어쩌면 당신은 그들이 지상에 도달 할 때 하늘에서 떨어지는 낙하산을 가지고 오래된 DOS 게임, 그들은 대포쪽으로 이동하는 것이 기억 나는 게임 업데이트 루프에서 3 초의 지연 시간을 갖는 함수 호출

배경의 비트가 ...뿐만 아니라 유래 여기에 묻는 생각 . 10 명이 들어가면 폭발합니다. 캐논 주인이 땅을하기 전에 모든 낙하산 병을 쏘고 싶습니다. 그래서 저는 java에서만 그렇게하고 있습니다.

Slick을 전혀 사용하지 않은 분들을 위해, 물건을 초기화하는 init() 함수, 모든 것을 화면에 렌더링하는 역할을하는 render() 함수가 있습니다. 기본적으로 게임 루프 자체 인 update() 함수가 있습니다. 모든 업데이트가 거기에서 발생하고 그에 따라 함수 렌더링이 렌더링됩니다.

예를 들어 3 초마다 임의의 X에서 낙하산 약탈자를 떨어 뜨리려고합니다.

queuedObject를 보유하고있는 ArrayList가 있습니다. 각 업데이트에서 객체는 update() 함수에서 파생 된 델타를 기반으로 배포 할 날씨 시간을 결정한 함수를 사용합니다. 존재하는 경우, 그 오브젝트는 렌더링 기능으로 불려 가고있는 다른 ArrayList에 전송됩니다. 따라서 객체가 renderList로 전송 될 때마다 렌더링됩니다. 문제는 업데이트 방법이 매우 빠릅니다. 그래서 제가 끝까지 얻은 것은 모든 오브젝트가 순간적으로 스크린으로 렌더링되는 것입니다. 예를 들어 매 3 초마다 한 번에 하나씩 렌더링됩니다.

Thread.sleep() 기술을 구현해 보았습니다. 그러나 그것은 Slick과 잘 작동하지 않았습니다. 나는 TimerTaks와 schedualer와 함께 작업을 시도했지만 그것을 사용하는 방법을 알아낼 couldnt ... 누군가가 올바른 방향으로 나를 가리킨 수 있을까요? 고맙습니다!!

낙하산 개체 :

package elements; 

import java.awt.Rectangle; 
import java.util.Random; 

import org.newdawn.slick.Image; 
import org.newdawn.slick.SlickException; 

public class Paratrooper1 { 

//private int strength = 100; 
private float yd; 
private float x; 
private float y; 
private int width; 
private int height; 
private boolean visible; 
private Image paratrooperImage; 

private int time; 

private Random random; 

public Paratrooper1() throws SlickException { 
    random = new Random(); 
    paratrooperImage = new Image("/res/paratrooper1.png"); 
    width = paratrooperImage.getWidth(); 
    height = paratrooperImage.getHeight(); 
    this.x = generateX(); 
    this.y = 0; 
    visible = true; 
    time = 0; 
} 

public Image getParaImage(){ 
    return paratrooperImage.getScaledCopy(0.2f); 
} 

public void Move(int delta){ 
    yd += 0.1f * delta; 
    if(this.y+yd > 500){ 
     this.x = generateX(); 
     this.y = 0; 
    }else{ 
     this.y += yd; 
     yd = 0; 
    } 
} 

public int getX(){ 
    return (int) x; 
} 

public int getY(){ 
    return (int) y; 
} 

public boolean isVisisble(){ 
    return visible; 
} 

public void setVisible(boolean tof){ 
    visible = tof; 
} 

public Rectangle getBound(){ 
    return new Rectangle((int)x,(int)y,width,height); 
} 

private int generateX(){ 
    return random.nextInt(940)+30; 
} 

public boolean isReadyToDeploy(int delta) { 
    float pastTime = 0; 
    pastTime += delta; 

    long test = System.currentTimeMillis(); 
    if(test >= (pastTime + 3 * 1000)) { //multiply by 1000 to get milliseconds 
     return true; 
    }else{ 
     return false; 
    } 
} 

}

AND 게임 CODE :

package javagame; 

import java.util.ArrayList; 

import org.newdawn.slick.GameContainer; 
import org.newdawn.slick.Graphics; 
import org.newdawn.slick.Image; 
import org.newdawn.slick.Input; 
import org.newdawn.slick.SlickException; 
import org.newdawn.slick.state.BasicGameState; 
import org.newdawn.slick.state.StateBasedGame; 

import elements.Paratrooper1; 

public class Play extends BasicGameState{ 

Paratrooper1 para1; 

private Image cursor; 
private int mousePosX = 0; 
private int mousePosY = 0; 
private String mouseLocationString = ""; 
private int score; 
private ArrayList<Paratrooper1> renderParatroopers; 
private ArrayList<Paratrooper1> queuedParatroopers; 

private int time; 


public Play(int state){ 
} 

public void init(GameContainer gc, StateBasedGame sbg) throws SlickException{ 
    score = 0; 
    time = 0; 

    renderParatroopers = new ArrayList<Paratrooper1>(); 

    //populate arraylist with paratroopers 
    queuedParatroopers = new ArrayList<Paratrooper1>(); 
    for (int i=0; i<5; i++){ 
     queuedParatroopers.add(new Paratrooper1()); 
    } 

    cursor = new Image("res/cursor.png"); 
    cursor.setCenterOfRotation(cursor.getWidth()/2, cursor.getHeight()/2); 
    gc.setMouseCursor(cursor.getScaledCopy(0.1f), 0, 0); 

    para1 = new Paratrooper1(); 
} 

public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException{ 
    g.drawString(mouseLocationString, 50, 30); 
    g.drawString("Paratrooper location: X:" +para1.getY()+ " Y:" +para1.getY(), 50, 45); 
    g.drawString("Current score: " +score, 800, 30); 

    //go through arraylist and render each paratrooper object to screen 
    if (renderParatroopers != null){ 
     for (int i = 0; i < renderParatroopers.size(); i++) { 
      Paratrooper1 para1 = (Paratrooper1)renderParatroopers.get(i); 
      if(para1.isVisisble()){ 
       g.drawImage(para1.getParaImage(),para1.getX(),para1.getY()); 
      } 
     }  
    } 
} 

public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException{ 
    Input input = gc.getInput(); 
    mousePosX = input.getMouseX(); 
    mousePosY = input.getMouseY(); 
    mouseLocationString = "Pointer location --- X:" +mousePosX+ " Y:" +mousePosY; 


    for (int i=0; i<queuedParatroopers.size(); i++){ 
     if (queuedParatroopers.get(i).isReadyToDeploy(delta)){ 
      renderParatroopers.add(queuedParatroopers.get(i)); 
     } 
    } 

    //update the x and y of each paratrooper object. 
    //Move() method accepts the delta and is calculated in to 
    //create a new x and y. Render method will update accordingly. 
    if(renderParatroopers != null){ 
     for (Paratrooper1 para : renderParatroopers){ 
      para.Move(delta); 
     } 
    } 
} 

/*private boolean isItTimeToDeploy(int deltaVar) { 
    float pastTime = 0; 
    pastTime += deltaVar; 

    long test = System.currentTimeMillis(); 
    if(test >= (pastTime + 3*1000)) { //multiply by 1000 to get milliseconds 
     return true; 
    }else{ 
     return false; 
    } 
}*/ 


public int getID(){ 
    return 1; 
} 

}

+3

이 짧은 버전에서 문제를 설명 할 수 있습니까? – Nishant

+0

권. 죄송합니다. 3 초마다 낙하산 조종 장치를 만들려고합니다. 나는 그것을 화면 상단에서 떨어 뜨리고 싶다. 나는 카운터를 만들거나 그것을 놓을 곳을 찾아 낼 수 없다. 너희들에게서 정보를 찾고있어. –

+0

try catch 블록에서 Thread.sleep (3000) 함수를 사용할 수 있습니다. – chrome

답변

1

pastTime는 인스턴스 변수되어야 로컬 변수이다. 대신에이 버전을 시도해보십시오

long pastTime = 0; 
public boolean isReadyToDeploy(long delta) { 
    if(pastTime < 3 * 1000) { //multiply by 1000 to get milliseconds 
     pastTime += delta; 
     return false; 
    }else{ 
     pastTime = 0; 
     return true; 
    } 
} 

long previousTime = 0; 

public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException{ 
    long tmp = System.currentTimeMillis(); 
    long customDelta = tmp - previousTime; 
    previousTime = tmp; 

    Input input = gc.getInput(); 
    mousePosX = input.getMouseX(); 
    mousePosY = input.getMouseY(); 
    mouseLocationString = "Pointer location --- X:" +mousePosX+ " Y:" +mousePosY; 

    for (int i=0; i<queuedParatroopers.size(); i++){ 
     if (queuedParatroopers.get(i).isReadyToDeploy(customDelta)){ 
      renderParatroopers.add(queuedParatroopers.get(i)); 
     } 
    } 

    //update the x and y of each paratrooper object. 
    //Move() method accepts the delta and is calculated in to 
    //create a new x and y. Render method will update accordingly. 
    if(renderParatroopers != null){ 
     for (Paratrooper1 para : renderParatroopers){ 
      para.Move(delta); 
     } 
    } 
} 
+0

우우! 다 좋아! 고맙습니다. 지금 당장! –

+0

좋아. 진행 상황이 있습니다. 나는이 방법을 사용했다. Play 클래스 (update 메소드() 밖)에 넣으려고했으나 Paratrooper 클래스를 통해이 클래스를 사용해 보았습니다. 내가 지금 가지고있는 것은 5 명의 낙하산 동물들이 모두 빠르기 때문에 빠르기 때문에 빠르며 빠르다. 나는 델타 값에 문제가 있다고 생각하고있다. 값을 디버깅하려고 시도했을 때 간단히 일치하지 않습니다. 델타에서 15를 얻었고 CurrentTimeMillis()에서 123131230102 정도를 얻었습니다. 그들은 어떻게 비교 될 수 있습니까? –

+0

Slick에서 delta가 어떻게 생성되는지 잘 모르겠습니다. 아마도 System.currentTimeMillis() 메서드를 사용하여 직접 계산할 수 있습니다. 필자는 테스트하지 않고 코드를 작성한다는 것을 명심하십시오. 다음은 작동 할 수있는 기능입니다 (원래 답변에 추가됨). – Mirks