I'm trying to create and extended class from the one bellow but I'm getting an error message from eclipse saying "Syntax error on token "{", { expected after this token"
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Vector2;
public class Ship {
protected int hull;
protected int shield;
protected Vector2 velocity;
protected int energy;
protected Texture shipTexture;
protected Vector2 position;
public Texture getShipTexture() {
return shipTexture;
}
public void setShipTexture(Texture shipTexture) {
this.shipTexture = shipTexture;
}
public Vector2 getPosition() {
return position;
}
public void setPosition(Vector2 position) {
this.position = position;
}
public int getHull() {
return hull;
}
public void setHull(int hull) {
this.hull = hull;
}
public int getShield() {
return shield;
}
public void setShield(int shield) {
this.shield = shield;
}
public Vector2 getVelocity() {
return velocity;
}
public void setVelocity(Vector2 velocity) {
this.velocity = velocity;
}
public int getEnergy() {
return energy;
}
public void setEnergy(int energy) {
this.energy = energy;
}
}
for this class after the first bracket:
public class Frigate extends Ship {
this.hull = 10;
this.shield = 10;
}
Is there a better way to set up "ships" with the same variables and actions but with different values?
It looks like you're attempting to initialize instance variables for your Frigate. Place that code inside a constructor.
public Frigate()
{
this.hull = 10;
this.shield = 10;
}
I would create a constructor fir Ship that accepts the two values:
protected Ship(int hull, int shield) {
this.hull = hull;
this.shield = shield;
}
Then call it from the subclass:
public class Frigate extends Ship {
public Frigate {
super(10, 10);
}
You should consider making Ship abstract as well, if it's just a "base" class.
Related
The task is to write an implementation of the smart robot class, which inherits from the regular robot class.
The main problem: no other classes in "robot" can be changed, even slightly.
It is necessary to redefine the robot's methods so that they both perform an action in the parent version (change coordinates), and simultaneously count the number of steps.
public class Main {
public static void main(String[] args) {
SmartRobot robot = new SmartRobot();
robot.moveDown();
robot.moveDown();
robot.moveLeft();
robot.moveUp();
robot.moveDown();
robot.moveLeft();
robot.moveLeft();
System.out.println("Координаты робота: " + robot.getX() + ":" + robot.getY());
System.out.println("Количество шагов: " + robot.getStepsCount());
}
}
class Robot {
private int x;
private int y;
public void moveRight() {
x++;
}
public void moveLeft() {
x--;
}
public void moveUp() {
y--;
}
public void moveDown() {
y++;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
class SmartRobot extends Robot {
#Override
public void moveRight() {
super.moveRight();
}
#Override
public void moveLeft() {
super.moveLeft();
}
#Override
public void moveUp() {
super.moveUp();
}
#Override
public void moveDown() {
super.moveDown();
}
#Override
public int getX() {
return super.getX();
}
#Override
public int getY() {
return super.getY();
}
public int getStepsCount() {
return getX() + getY();
}
}
X and Y are not the number of your steps. Especially there are minus move such as moveUp and moveLeft.
You can add a member as step counter in SmartRobot, and then make it plus 1 in each moves.
I need to compare all objects in the ArrayList players, and have it return the top 3 players in terms of total points for the season (In the TopPoints method).
There are 5 players objects in the ArrayList, and their total points are: 379, 330, 313, 157, & 153. I know I need to compare them using TotalPts, but I'm drawing a blank.
Can anyone help guide me in the right direction?
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class Roster {
static ArrayList <Player> players = new ArrayList<Player> ();
public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\tpurv_000\\Desktop\\Stats.txt");
Scanner scan = new Scanner(file);
scan.useDelimiter("\\r?\\n");
scan.nextLine(); // ignores first line, since it's a header
while(scan.hasNextLine()) {
String[] values = scan.nextLine().split("\t");
Player currentPlayer = new Player();
currentPlayer.setPlayerNum(Integer.parseInt(values[0]));
currentPlayer.setPlayerName(values[1]);
currentPlayer.setGP(Integer.parseInt(values[2]));
currentPlayer.setGS(Integer.parseInt(values[3]));
currentPlayer.setTotalMins(Integer.parseInt(values[4]));
currentPlayer.setTotalFG(Integer.parseInt(values[5]));
currentPlayer.setTotalFGA(Integer.parseInt(values[6]));
currentPlayer.setThreeFG(Integer.parseInt(values[7]));
currentPlayer.setThreeFGA(Integer.parseInt(values[8]));
currentPlayer.setFT(Integer.parseInt(values[9]));
currentPlayer.setFTA(Integer.parseInt(values[10]));
currentPlayer.setOffReb(Integer.parseInt(values[11]));
currentPlayer.setDefReb(Integer.parseInt(values[12]));
currentPlayer.setPF(Integer.parseInt(values[13]));
currentPlayer.setA(Integer.parseInt(values[14]));
currentPlayer.setTO(Integer.parseInt(values[15]));
currentPlayer.setSTL(Integer.parseInt(values[16]));
currentPlayer.setBLK(Integer.parseInt(values[17]));
currentPlayer.setTotalPts(Integer.parseInt(values[18]));
players.add(currentPlayer);
}
System.out.println(players);
TopPoints();
}
public static void TopPoints(){
int largest = 0;
int secondLargest = 0;
int thirdLargest = 0;
//Not sure how to compare
System.out.println(largest);
}
}
class Player {
private int playerNum, GP, GS, totalMins, totalFG, totalFGA, threeFG, threeFGA, FT, FTA, offReb, defReb, PF, A, TO, STL, BLK, totalPts;
private String playerName;
//accessors & mutators
public int getPlayerNum() {
return playerNum;
}
public void setPlayerNum(int playerNum) {
this.playerNum = playerNum;
}
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public int getGP() {
return GP;
}
public void setGP(int gP) {
GP = gP;
}
public int getGS() {
return GS;
}
public void setGS(int gS) {
GS = gS;
}
public int getTotalMins() {
return totalMins;
}
public void setTotalMins(int totalMins) {
this.totalMins = totalMins;
}
public int getTotalFG() {
return totalFG;
}
public void setTotalFG(int totalFG) {
this.totalFG = totalFG;
}
public int getTotalFGA() {
return totalFGA;
}
public void setTotalFGA(int totalFGA) {
this.totalFGA = totalFGA;
}
public int getThreeFG() {
return threeFG;
}
public void setThreeFG(int threeFG) {
this.threeFG = threeFG;
}
public int getThreeFGA() {
return threeFGA;
}
public void setThreeFGA(int threeFGA) {
this.threeFGA = threeFGA;
}
public int getFT() {
return FT;
}
public void setFT(int fT) {
FT = fT;
}
public int getFTA() {
return FTA;
}
public void setFTA(int fTA) {
FTA = fTA;
}
public int getOffReb() {
return offReb;
}
public void setOffReb(int offReb) {
this.offReb = offReb;
}
public int getDefReb() {
return defReb;
}
public void setDefReb(int defReb) {
this.defReb = defReb;
}
public int getPF() {
return PF;
}
public void setPF(int pF) {
PF = pF;
}
public int getA() {
return A;
}
public void setA(int a) {
A = a;
}
public int getTO() {
return TO;
}
public void setTO(int tO) {
TO = tO;
}
public int getSTL() {
return STL;
}
public void setSTL(int sTL) {
STL = sTL;
}
public int getBLK() {
return BLK;
}
public void setBLK(int bLK) {
BLK = bLK;
}
public int getTotalPts() {
return totalPts;
}
public void setTotalPts(int totalPts) {
this.totalPts = totalPts;
}
//Computing methods
public int avgMin() {
return (this.totalMins / this.GP);
}
public int fgPercentage() {
return (this.totalFG / this.totalFGA) * 100;
}
public int threefgPercentage() {
return (this.threeFG / this.threeFGA) * 100;
}
public int freethrowPercentage() {
return (this.FT / this.FTA) * 100;
}
public int avgRebounds() {
return (this.offReb + this.defReb) / 2;
}
}
There is a lot of solutions for it. You can use TreeList, for example, to sort all item at moment that it is added.
To sort an ArrayList, you should use Collections.sort() method. Take a look in this example:
public class ArrayListSortExample{
public static void main(String ... args){
List<Player> players = new ArrayList<>();
// Lets create 50 players with random score.
Random random = new Random();
for(int i = 0; i < 50; i++){
Player player = new Player();
player.setScore(random.nextInt(100));
players.add(player);
}
// Lets sort players by score
Collections.sort(players, new Comparator<Player>() {
#Override
public int compare(Player o1, Player o2) {
return o1.getScore() - o2.getScore();
}
});
// Print 3 top players
for(int i = 0; i < 3; i++){
System.out.println((i+1) + "º place: " + players.get(i).getScore() + " score");
}
}
public static class Player{
private int score;
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
}
I'm new to java and i was searching about this for a long time. How can I have access to the item's b variables in class Player??(the cod i'm posting is a part of my full programm so don't mind if you see methods or variables that are not declared in the following code)
import java.util.Random;
public abstract class Player {
private int x, y;
private String name;
private int pNumber;
private int mLine;
private int tLine;
private boolean possession;
private int c;
private int f = 0;
private int i = 0;
public int getPlx() {
return x;
}
public void setPlx(int x) {
this.x = x;
}
public int getPly() {
return y;
}
public void setPly(int y) {
this.y = y;
}
public String getPName() {
return name;
}
public void setPName(String name) {
this.name = name;
}
public int getPNum() {
return pNumber;
}
public void setPNum(int pNumber) {
this.pNumber = pNumber;
}
public int getMLine() {
return mLine;
}
public void setMLine(int mLine) {
this.mLine = mLine;
}
public int getLine() {
return tLine;
}
public void setTLine(int tLine) {
this.tLine = tLine;
}
public boolean getPos() {
return possession;
}
public void setPos(boolean possession) {
this.possession = possession;
}
private Random rand = new Random();
public void Move() { //me8odos metakinisis
c = rand.nextInt(2);
if (c == 0) {
y++;
} else {
y--;
}
}
public void Pass() {
if (this.possession == true) {
c = rand.nextInt(10);
while ((f == 0) && (i < 10)) {
if (main.barcelona.get(i).name == this.name) {}
}
}
}
public abstract void SpecialMove();
}
public class Ball {
private int x, y;
private Player formerP = null;
private Player currentP = null;
public Ball(int x, int y, Player formerP, Player currentP) {
this.x = x;
this.y = y;
this.formerP = formerP;
this.currentP = currentP;
}
public int getBX() {
return x;
}
public void setBX(int x) {
this.x = x;
}
public int getBY() {
return y;
}
public void setBY(int y) {
this.y = y;
}
void Assign(Player playerP) {
int px = playerP.getPlx();
if (this.currentP == null) {
if (((this.x - px <= 1) || (px - this.x) <= 1)
&& ((this.x - px <= 1) || (px - this.x) = 1)) {
this.currentP = playerP;
this.formerP.possession = false;
playerP.possession = true;
if (this.currentP.team == this.formerP.team) {
int pass = this.currentP.getPasses();
pass++;
this.currentP.setPasses(pass);
} else {
int mistake = this.currentP.getMistakes();
mistake++;
this.currentP.setMistakes(mistake);
}
}
}
this.formerP = this.currentP;
this.currentP = null;
this.formerP = null;
}
}
try BallClassName.getX();
You may have to make getX static
If you don't want to instantiate the class Ball in the Player class and you would like to ensure that all players are playing with the one and only ball, then consider making Ball a Singleton.
In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.
public class Ball {
private static Ball singletonBall;
private int x;
private int y;
private Player formerP;
private Player currentP;
public static Ball getSingletonBall() {
if(singletonBall == null){
singletonBall = new Ball();
}
return singletonBall;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Player getFormerP() {
return formerP;
}
public void setFormerP(Player formerP) {
this.formerP = formerP;
}
public Player getCurrentP() {
return currentP;
}
public void setCurrentP(Player currentP) {
this.currentP = currentP;
}
}
If there is something that you need inside Player that you will be using often that won't change throughout the life of the Player object (or sub object in your case), then you might as well pass it to a local variable through the Player constructor.
Let's assume Item B is the Ball and you have a Ball class.
So in player (or sub player) declare your object you want access to:
class Player {
Ball ball;
public Player(Ball ball) {
this.ball = ball;
}
Or if it's just something that you'll be using infrequently or something that's value will change (more likely with a ball), then create a method to perform what you need on the Player object.
class Player {
.
.
.
.
.
public void dribble(Ball ball) {
// do something with the ball
ball.setPosition(10, 20);
ball.update();
}
}
Then whatever instantiates Player can access that method.
public static void main(String[] args) {
Player player = new Player();
Ball ball = new Ball();
player.dribble(ball);
}
I have been having some issues with loading Textures in LWJGL/Slick Util. I am receiving this error in the texture.bind() method. I would also like advice as to how to improve my code if improvement is needed. Here it is:
The Sprite Class:
package geniushour.engine.animation;
import static org.lwjgl.opengl.GL11.*;
import java.io.IOException;
import org.newdawn.slick.opengl.Texture;
public class Sprite {
private float sx;
private float sy;
private Texture texture;
public Sprite(float sx, float sy, Texture texture) throws IOException{
this.texture = texture;
this.sx = sx;
this.sy = sy;
}
public void render(){
texture.bind();
glBegin(GL_QUADS);
glTexCoord2f(0,0);
glVertex2f(0,0);
glTexCoord2f(1,0);
glVertex2f(0,sy);
glTexCoord2f(1,1);
glVertex2f(sx,sy);
glTexCoord2f(0,1);
glVertex2f(sx,0);
glEnd();
}
public float getSX(){
return sx;
}
public float getSY(){
return sy;
}
public Texture getTexture(){
return texture;
}
public void setSX(float sx){
this.sx = sx;
}
public void setSY(float sy){
this.sy = sy;
}
/*public void setSpriteTexture(String key) throws IOException{
this.texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("img/"+key+".png"));
}*/
}
The GameObject Class:
package geniushour.gameobject;
import static org.lwjgl.opengl.GL11.glPopMatrix;
import static org.lwjgl.opengl.GL11.glPushMatrix;
import static org.lwjgl.opengl.GL11.glTranslatef;
import java.io.IOException;
import org.newdawn.slick.opengl.Texture;
import geniushour.engine.animation.Sprite;
public abstract class GameObject {
protected float x;
protected float y;
protected float sx;
protected float sy;
protected Sprite spr;
protected int type;
protected static final int PLAYER_ID = 0;
protected static final int ENEMY_ID = 1;
protected static final int ITEM_ID = 2;
protected static final int ENTITY_SIZE = 64;
protected static final int ITEM_SIZE = 16;
protected boolean[] flags = new boolean[1];
public void update(){}
public void render(){
glPushMatrix();
glTranslatef(x,y,0);
spr.render();
glPopMatrix();
}
public float getX(){
return x;
}
public float getY(){
return y;
}
public float getSX(){
return spr.getSX();
}
public float getSY(){
return spr.getSY();
}
public int getType(){
return type;
}
public boolean getRemove(){
return flags[0];
}
public void remove(){
flags[0] = true;
}
/*protected void setTexture(String key) throws IOException{
spr.setSpriteTexture(key);
}*/
public Texture getTexture(){
return spr.getTexture();
}
protected void init(float x, float y, float sx, float sy,Texture texture,int type) throws IOException{
this.x = x;
this.y = y;
this.type = type;
this.spr = new Sprite(sx,sy,texture);
}
}
The Player Class:
package geniushour.gameobject.entity;
import java.io.IOException;
import org.lwjgl.input.Keyboard;
import org.newdawn.slick.opengl.Texture;
import geniushour.game.Inventory;
import geniushour.game.Stats;
import geniushour.gameobject.GameObject;
import geniushour.gameobject.item.Item;
public class Player extends GameObject {
private Stats stats;
private Inventory inv;
private int stamina;
private int maxStamina = 150;
public Player(float x, float y, Texture texture) throws IOException{
init(x,y,ENTITY_SIZE,ENTITY_SIZE,texture,PLAYER_ID);
stats = new Stats(0,true);
inv = new Inventory(9);
stamina = maxStamina;
}
public void update(){
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) && stamina > 0){
stamina--;
}
else if(!Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)){
stamina++;
if(stamina > maxStamina){
stamina = maxStamina;
}
}
}
public void getInput(){
if(Keyboard.isKeyDown(Keyboard.KEY_W)){
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) && stamina > 0){
move(0,1.5);
}
else{
move(0,1);
}
}
if(Keyboard.isKeyDown(Keyboard.KEY_S)){
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) && stamina > 0){
move(0,-1.5);
}
else{
move(0,-1);
}
}
if(Keyboard.isKeyDown(Keyboard.KEY_A)){
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) && stamina != 0){
move(-1.5,0);
}
else{
move(-1,0);
}
}
if(Keyboard.isKeyDown(Keyboard.KEY_D)){
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) && stamina != 0){
move(1.5,0);
}
else{
move(1,0);
}
}
}
public Texture getTexture(){
return getTexture();
}
private void move(double magX, double magY){
x += getSpeed() * magX;
y += getSpeed() * magY;
}
private int getSpeed(){
return stats.getPlayerSpeed();
}
#SuppressWarnings("unused")
private int getLevel(){
return stats.getLevel();
}
#SuppressWarnings("unused")
private int getXP(){
return stats.getXP();
}
public int getMaxHP(){
return stats.getMaxHP();
}
public int getCurrentHealth(){
return stats.getCurrentHealth();
}
public int getStrength(){
return stats.getStrength();
}
public int getMagic(){
return stats.getMagic();
}
public void addXP(int amt){
stats.addXP(amt);
}
public void addHP(int amt){
stats.addHP(amt);
}
public void addItem(Item item){
inv.add(item);
}
}
The Game Class:
package geniushour.game;
import java.io.IOException;
import java.util.ArrayList;
import org.newdawn.slick.opengl.Texture;
import geniushour.gameobject.*;
import geniushour.gameobject.entity.*;
import geniushour.gameobject.item.*;
public class Game {
private ArrayList<GameObject> obj;
private ArrayList<GameObject> remove;
private Player p; private Texture pTexture;
private ItemEssence essence; private Texture eTexture;
private EnemyBlob blob; private Texture bTexture;
public Game() throws IOException{
obj = new ArrayList<GameObject>();
remove = new ArrayList<GameObject>();
setTexture(pTexture,"raptor");
setTexture(eTexture,"essence");
setTexture(bTexture,"blob");
p = new Player(250,250,pTexture);
essence = new ItemEssence(400, 400, eTexture, p);
blob = new EnemyBlob(300,500,bTexture, 1);
obj.add(essence);
obj.add(p);
obj.add(blob);
}
public void getInput(){
p.getInput();
}
public void update(){
for(GameObject go : obj){
if(!go.getRemove()){
go.update();
}
else{
remove.add(go);
}
}
for(GameObject go : remove){
obj.remove(go);
}
}
public void render(){
for(GameObject go : obj){
go.render();
}
}
public ArrayList<GameObject> sphereCollide(float x, float y, float radius){
ArrayList<GameObject> res = new ArrayList<GameObject>();
for(GameObject go : obj){
if(Util.dist(go.getX(),x,go.getY(),y) < radius){
res.add(go);
}
}
return res;
}
private void setTexture(Texture texture, String key){
}
}
The error occurs in the Sprite class, the first block of code.
I'm currently following this book to create my libgdx game..
So far, i have these classes to create my game :
AbstractGameScreen.java - that Implements libgdx's Screen
AbstractGameObject.java - that extends libgdx's Actor
GamePlay.java - which is my game screen
GameController.java - where i init my game objects
GameRenderer.java - when i render all my objects
Assets.java - a class that organizes my game assets
Ring.java - an object in my game
And here is my code..
AbstractGameScreen
public abstract class AbstractGameScreen implements Screen {
protected Game game;
public AbstractGameScreen(Game game){
this.game = game;
}
public abstract void render(float deltaTime);
public abstract void resize(int width, int height);
public abstract void show();
public abstract void hide();
public abstract void pause();
public void resume(String bg, String ring){
Assets.instance.init(new AssetManager(), bg, ring); // kosongin, jadinya default
}
public void dispose(){
Assets.instance.dispose();
}
}
AbstractGameObject
public abstract class AbstractGameObject extends Actor{ //implements EventListener{ //extends Sprite{
public Vector2 position;
public Vector2 dimension;
public Vector2 origin;
public Vector2 scale;
public float rotation;
public AbstractGameObject(){
position = new Vector2();
dimension = new Vector2(1, 1);
origin = new Vector2();
scale = new Vector2(1, 1);
rotation = 0;
}
public void update (float deltaTime){
}
public abstract void render(SpriteBatch batch);
}
GamePlay
public class GamePlay extends AbstractGameScreen implements InputProcessor{
private GameController gameController;
private GameRenderer gameRenderer;
private String dummyBg, dummyRing;
private boolean paused;
// for touch purposes
private static final int appWidth = Constants.VIEWPORT_GUI_WIDTH_INT;
private static final int appHeight = Constants.VIEWPORT_GUI_HEIGHT_INT;
public GamePlay(Game game) {
super(game);
// still dummy.. nantinya ngambil dari database nya
this.dummyBg = "bg-default";
this.dummyRing = "ring-default";
Gdx.input.setInputProcessor(this);
}
#Override
public void render(float deltaTime) {
if(!paused){
gameController.update(deltaTime);
}
//Gdx.gl.glClearColor(0x64 / 255.0f, 0x95 / 255.0f,0xed / 255.0f, 0xff / 255.0f);
//Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// render game nya
gameRenderer.render();
}
#Override
public void resize(int width, int height) {
gameRenderer.resize(width, height);
}
#Override
public void show() {
Assets.instance.init(new AssetManager(), "bg-default", "ring-default");
Gdx.app.log("GamePlay", "After show() method");
gameController = new GameController(game);
gameRenderer = new GameRenderer(gameController);
Gdx.input.setCatchBackKey(true);
}
#Override
public void hide() {
gameRenderer.dispose();
Gdx.input.setCatchBackKey(false);
}
#Override
public void dispose(){
gameRenderer.dispose();
Assets.instance.dispose();
}
#Override
public void pause() {
paused = true;
}
#Override
public void resume() {
super.resume(this.dummyBg, this.dummyRing);
//Assets.instance.init(new AssetManager(), this.dummyBg, this.dummyRing);
paused = false;
}
#Override
public boolean keyDown(int keycode) {
return false;
}
#Override
public boolean keyUp(int keycode) {
return false;
}
#Override
public boolean keyTyped(char character) {
return false;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
return true;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return true;
}
// for touch purposes
private float getCursorToModelX(int screenX, int cursorX) {
return (((float)cursorX) * appWidth) / ((float)screenX);
}
private float getCursorToModelY(int screenY, int cursorY) {
return ((float)(screenY - cursorY)) * appHeight / ((float)screenY) ;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
#Override
public boolean scrolled(int amount) {
return false;
}
}
GameController
public class GameController extends InputAdapter{
// game objects
public Array<Tiang> tiangs;
public Array<Ring> rings;
//private Game game;
// game decorations
public Background background; public Sprite[] testSprite;
private Game game;
public GameController(Game game){
this.game = game;
init();
}
private void init(){
// preparing variables
rings = new Array<Ring>();
tiangs = new Array<Tiang>();
initObjects();
initDecorations();
initGui();
}
private void initObjects(){
AbstractGameObject obj = null;
obj = new Ring(1, "default");
obj.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
//super.clicked(event, x, y);
Gdx.app.log("tag", "test clisk");
}
});
rings.add((Ring)obj);
}
private void initDecorations(){
}
private void initGui(){
}
private void handleInput(float deltatime){
}
public void update(float deltaTime){
//if(Gdx.input.isTouched()){
// Gdx.app.log("update", "screen touched");
//}
}
}
GameRenderer
public class GameRenderer implements Disposable{
private OrthographicCamera camera;
private GameController controller;
private SpriteBatch batch;
public GameRenderer(GameController controller){
this.controller = controller;
init();
}
private void init(){
batch = new SpriteBatch();
camera = new OrthographicCamera(Constants.VIEWPORT_WIDTH, Constants.VIEWPORT_HEIGHT); //diambil dari class "Constants" (di package util)
camera.position.set(0, 0, 0);
camera.update();
}
public void resize(int width, int height){
camera.viewportWidth = (Constants.VIEWPORT_HEIGHT / height) * width;
camera.update();
}
public void render(){
renderGui();
renderDecorations();
renderObjects();
}
private void renderGui(){
}
private void renderDecorations(){
}
private void renderObjects(){
batch.setProjectionMatrix(camera.combined);
batch.begin();
for(Ring rings : controller.rings){
rings.render(batch);
}
batch.end();
}
#Override
public void dispose() {
}
}
Assets
public class Assets implements Disposable, AssetErrorListener{
public static final String TAG = Assets.class.getName();
public static final Assets instance = new Assets();
private AssetManager assetManager;
// inner class objects
public AssetTiang tiang;
public AssetBackgroud bg;
public AssetTombol tombol;
public AssetTombolBg tombolBg;
public AssetRing ring;
//singleton pattern, buat mencegah instansiasi dari class yang lain
private Assets(){}
//public void init(AssetManager assetManager){
public void init(AssetManager assetManager, String jenisBg, String jenisRing){
this.assetManager = assetManager;
assetManager.setErrorListener(this);
//load texture atlas yang udah dibikin pake TexturePacker nya (liat ebook page 167)
assetManager.load(Constants.TEXTURE_ATLAS_OBJECTS, TextureAtlas.class);
assetManager.load(Constants.TEXTURE_ATLAS_DECORATION, TextureAtlas.class);
assetManager.load(Constants.TEXTURE_ATLAS_GUI, TextureAtlas.class);
// inner class objects
tiang = new AssetTiang(atlasObject);
bg = new AssetBackgroud(atlasDecoration, jenisBg);
tombol = new AssetTombol(atlasGui);
tombolBg = new AssetTombolBg(atlasDecoration);
ring = new AssetRing(atlasObject, jenisRing);
}
#Override
public void error(AssetDescriptor asset, Throwable throwable) {
// TODO Auto-generated method stub
}
#Override
public void dispose(){
assetManager.dispose();
}
public class AssetRing{
public final AtlasRegion ring;
// jenis ring dimasukin disini, karena jenis ring bisa diganti-ganti sesuai yang dipilih
public AssetRing(TextureAtlas atlas, String jenisRing){
if(!jenisRing.equals("")){
ring = atlas.findRegion(jenisRing);
}
else{
ring = atlas.findRegion("ring-default");
}
}
}
}
And finally, Ring (Object)
public class Ring extends AbstractGameObject{
private TextureRegion ringOverLay;
private float length;
// jenis ring nya
public String jenis;
public Ring(float length, String jenis){
init();
setLength(length);
setJenis(jenis);
}
// getters
public float getLength(){
return this.length;
}
public String getJenis(){
return this.jenis;
}
public Vector2 getPosition(){
return position;
}
// setters
public void setLength(float length){
this.length = length;
dimension.set(5.0f, 1.0f);
}
public void setJenis(String jenis){
this.jenis = jenis;
}
public void setPosition(float x, float y){
position.set(x, y);
}
private void init(){
ringOverLay = Assets.instance.ring.ring; // Assets.instance.namaobjek.atlasregion
origin.x = dimension.x/2; // -dimension.x/2;
origin.y = dimension.y/2;
position.x = -5.0f;
position.y = -2.5f;
}
#Override
public void render(SpriteBatch batch) {
TextureRegion reg = null;
reg = ringOverLay;
batch.draw(reg.getTexture(), position.x, position.y, origin.x, origin.y, dimension.x, dimension.y, scale.x, scale.y, rotation, reg.getRegionX(), reg.getRegionY(), reg.getRegionWidth(), reg.getRegionHeight(), false, false);
}
}
So what's the problem? Okay, the problem is i cannot make the Ring (game object) become clickable.. the Ring is extending AbstractGameObject (which is Actor), and, in the GameController i've add a ClickListener to the Ring object, but the object still unclickable..
Please, anyone tell me what's my mistake?
You're using your Actor (in your case, the Ring) incorrectly: Actors are part of Scene2d, and as such must follow precise rules to work correctly.
To answer your question more specifically, Ring needs to be added to a Stage which itself is an InputProcessor. The Stage is responsible to distribute the input events (such as touch events) to the its Actors. Without defining a Stage your Actors will not respond to any input events.
Read up on Scene2d from the link above. This video tutorial is also helpful.